package com.ytjj.qmyx.supplychain.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.kuaidi100.sdk.request.ChannelSpecRequest;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.api.ResultCode;
import com.ytjj.qmyx.supplychain.common.constants.QueueConstants;
import com.ytjj.qmyx.supplychain.common.constants.RedisConstants;
import com.ytjj.qmyx.supplychain.common.enums.IsZeroProductEnums;
import com.ytjj.qmyx.supplychain.common.enums.ShopProductReceiveStatusEnums;
import com.ytjj.qmyx.supplychain.common.enums.StockFrozenRecordStatusEnums;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.dto.ProductCategoryDto;
import com.ytjj.qmyx.supplychain.common.model.dto.ProductDto;
import com.ytjj.qmyx.supplychain.common.model.request.YxAssignFreight;
import com.ytjj.qmyx.supplychain.common.model.request.*;
import com.ytjj.qmyx.supplychain.common.model.response.*;
import com.ytjj.qmyx.supplychain.common.utils.HttpClientUtil;
import com.ytjj.qmyx.supplychain.common.utils.OrderUtils;
import com.ytjj.qmyx.supplychain.common.utils.RedisService;
import com.ytjj.qmyx.supplychain.mapper.*;
import com.ytjj.qmyx.supplychain.mapper.entity.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.cglib.beans.BeanMap;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Slf4j
@Service
@RefreshScope
public class ProductService {
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductSpecMapper productSpecMapper;
    @Resource
    private StockFrozenRecordMapper stockFrozenRecordMapper;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private BankerProductMapper bankerProductMapper;
    @Resource
    private BankerProductSkuKeyMapper bankerProductSkuKeyMapper;
    @Resource
    private BankerProductSkuValueMapper bankerProductSkuValueMapper;
    @Resource
    private BankerProductSpecMapper bankerProductSpecMapper;
    @Resource
    private BankerProductImgMapper bankerProductImgMapper;
    @Resource
    private ShopProductReceiveRecordMapper shopProductReceiveRecordMapper;
    @Resource
    private NotifyUrlInfoMapper notifyUrlInfoMapper;
    @Resource
    private ProductImgMapper productImgMapper;
    @Autowired
    private ProductCategoryService productCategoryService;
    @Autowired
    private BankerService bankerService;
    @Resource
    private ProductSkuKeyMapper productSkuKeyMapper;
    @Resource
    private ProductSkuValueMapper productSkuValueMapper;
    @Resource
    private BankerMessageMapper bankerMessageMapper;
    @Resource
    private BankerMapper bankerMapper;
    @Resource
    private BankerApplyMapper bankerApplyMapper;
    @Resource
    private ProductLabelProductMapper productLabelProductMapper;
    @Resource
    private ProductLabelMapper productLabelMapper;
    @Resource
    private FreightTemplateDao freightTemplateDao;
    @Resource
    private ProductBatchRuleMapper productBatchRuleMapper;
    @Resource
    private ProductBatchPriceMapper productBatchPriceMapper;
    @Resource
    private RedisService redisService;
    @Resource
    private ShopInfoMapper shopInfoMapper;
    @Resource
    private ProductImportMsgMapper productImportMsgMapper;
    @Resource
    private ProductImportInfoMsgMapper productImportInfoMsgMapper;
    /**
     * 是否允许调高成本价
     * 1-允许 0-不允许
     */
    @Value("${rise_price.switch:1}")
    private Integer risePriceSwitch;

    @Resource(name="guchuangRabbitTemplate")
    private RabbitTemplate guchuangRabbitTemplate;
//    @Resource(name = "jumaiduoRabbitTemplate")
//    private RabbitTemplate jumaiduoRabbitTemplate;
//    @Resource(name = "yiquanRabbitTemplate")
//    private RabbitTemplate yiquanRabbitTemplate;
//    @Resource(name = "zxlpRabbitTemplate")
//    private RabbitTemplate zxlpRabbitTemplate;
//    @Resource(name = "ygyxRabbitTemplate")
//    private RabbitTemplate ygyxRabbitTemplate;
//
//    @Resource(name = "yxhdRabbitTemplate")
//    private RabbitTemplate yxhdRabbitTemplate;
//
//    @Resource(name = "jckjRabbitTemplate")
//    private RabbitTemplate jckjRabbitTemplate;

    /**
     * 获取商品详情
     * @param id
     * @return
     */
    public ProductResponse getById(Integer id) {
        YxProduct product = productMapper.selectByPrimaryKey(id);
        List<ProductSkuKeyResponse> skuKey = productMapper.findSku(id);
        List<ProductImgResponse> bannerList = productMapper.findImg(id, "banner");
        List<ProductImgResponse> infoList = productMapper.findImg(id, "info");
        List<ProductSpecResponse> spec = productMapper.findSpec(id);
        List<ProductLabelVO> productLabel = productMapper.findProductLabel(id);

        ProductResponse productResponse = ProductResponse.builder()
                .id(product.getId())
                .productName(product.getProductName())
                .productImg(product.getProductImg())
                .descr(product.getDescr())
                .stock(product.getStock())
                .brand(product.getBrand())
                .supplyPrice(product.getSupplyPrice())
                .costPrice(product.getCostPrice())
                .salePrice(product.getSalePrice())
                .topCategoryId(product.getTopCategoryId())
                .categoryId(product.getCategoryId())
                .bottomCategoryId(product.getBottomCategoryId())
                .typeno(product.getTypeno())
                .bannerList(bannerList)
                .infoList(infoList)
                .skuKey(skuKey)
                .spec(spec)
                .productLabel(productLabel)
                .supplyPrice(product.getSupplyPrice())
                .build();
        return productResponse;
    }

    public CommonPage<ProductSelectResponse> findProduceSelect(ProductSelectRequest request) {
        if (null != request.getProductLabelId()){
            Example example = new Example(YxProductLabelProduct.class);
            example.createCriteria().andEqualTo("productLabelId", request.getProductLabelId());
            List<YxProductLabelProduct> productLabelProducts = productLabelProductMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(productLabelProducts)){
                return CommonPage.restPage(new ArrayList<>());
            }
            List<Integer> collect = productLabelProducts.stream().map(YxProductLabelProduct::getProductId).collect(Collectors.toList());
            request.setProductIds(collect);
        }
        if (null != request.getShopId()){
            String shopIds = shopInfoMapper.selectByShopId(request.getShopId());
            if(org.apache.commons.lang3.StringUtils.isBlank(shopIds)){
                return CommonPage.restPage(new ArrayList<>());
            }
            String[] split = shopIds.split(",");
            request.setShopIds(Arrays.asList(split));
        }
        log.info("查询选品中心商品日志：{}",JSONObject.toJSONString(request));
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<ProductSelectResponse> productList = productMapper.findProduceSelect(request);
        if (CollectionUtils.isEmpty(productList)) {
            return CommonPage.restPage(new ArrayList<>());
        }
        Example shopInfoExample = new Example(YxShopInfo.class);
        shopInfoExample.createCriteria().andEqualTo("shopId",request.getShopId());
        List<YxShopInfo> yxShopInfos = shopInfoMapper.selectByExample(shopInfoExample);
        productList.stream().forEach(item ->{
            Example example = new Example(YxProductLabelProduct.class);
            example.createCriteria().andEqualTo("productId", item.getId());
            List<YxProductLabelProduct> productLabelProducts = productLabelProductMapper.selectByExample(example);
            List<Integer> productLabelIds = productLabelProducts.stream().map(YxProductLabelProduct::getProductLabelId).collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(productLabelIds)) {
                Example example1 = new Example(YxProductLabel.class);
                example1.createCriteria().andIn("productLabelId", productLabelIds);
                List<YxProductLabel> productLabels = productLabelMapper.selectByExample(example1);
                item.setLabelNames(Joiner.on(",").join(productLabels.stream().map(YxProductLabel::getProductLabelName).collect(Collectors.toList())));
            }
            item.setIsSelected(request.getIsSelected());
            if (!CollectionUtils.isEmpty(yxShopInfos) && yxShopInfos.get(0).getPlateform() == 2){
                item.setMinCostPrice("0");
                item.setMaxCostPrice("0");
            }
        });
        return CommonPage.restPage(productList);
    }

    /**
     * 查询商品列表信息
     * @param request
     * @return
     */
    public CommonPage queryAll(ProductRequest request) {
        //如果是选择排除已选择的，则走if中的结果
        if (ShopProductReceiveStatusEnums.UN_ACTIVATION.getStatus().equals(request.getReceiveStatus())) {
            PageHelper.startPage(request.getPageNum(), request.getPageSize());
            List<SupplyProductListResponse> productList = productMapper.getProductNotIncludReceived(request);
            if (CollectionUtils.isEmpty(productList)) {
                return CommonPage.restPage(new ArrayList<>());
            }
            handleCategoryInfo(productList);
            return CommonPage.restPage(productList);
        }
        if(null != request.getProductLabelId()){
            Example example = new Example(YxProductLabelProduct.class);
            example.createCriteria().andEqualTo("productLabelId",request.getProductLabelId());
            List<YxProductLabelProduct> yxProductLabelProducts = productLabelProductMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(yxProductLabelProducts)){
                List<Integer> productIds = yxProductLabelProducts.stream().map(YxProductLabelProduct::getProductId).collect(Collectors.toList());
                request.setProductIds(productIds);
            }else {
                return CommonPage.restPage(new ArrayList<>());
            }
        }

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<SupplyProductListResponse> list = productMapper.selectSupplyProductAll(request);
        if (CollectionUtils.isEmpty(list)) {
            return CommonPage.restPage(new ArrayList<>());
        }

        Example shopExample = new Example(YxShopInfo.class);
        shopExample.selectProperties("name", "shopId");
        List<YxShopInfo> shopList = shopInfoMapper.selectByExample(shopExample);
        list.stream().forEach(item -> {
            BigDecimal grossProfit = new BigDecimal(0);
            String grossProfixRate = "0.00";
            if (null == item.getSupplyPrice()) {
                item.setSupplyPrice(new BigDecimal("0"));
            }
            if (null != item.getSupplyPrice() && item.getSupplyPrice().compareTo(BigDecimal.ZERO) != 0 ) {
                grossProfit = item.getSupplyPrice().subtract(item.getCostPrice()).divide(item.getSupplyPrice(), 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
                DecimalFormat df = new DecimalFormat("0.00");
                grossProfixRate = df.format(grossProfit);
            }
            Example example = new Example(YxProductLabelProduct.class);
            example.createCriteria().andEqualTo("productId", item.getId());
            List<YxProductLabelProduct> productLabelProducts = productLabelProductMapper.selectByExample(example);
            List<Integer> productLabelIds = productLabelProducts.stream().map(YxProductLabelProduct::getProductLabelId).collect(Collectors.toList());
            item.setProductLabelIds(productLabelIds);

            if (!CollectionUtils.isEmpty(productLabelIds)) {
                Example example1 = new Example(YxProductLabel.class);
                example1.createCriteria().andIn("productLabelId", productLabelIds);
                List<YxProductLabel> productLabels = productLabelMapper.selectByExample(example1);
                item.setProductLabelName(Joiner.on(",").join(productLabels.stream().map(YxProductLabel::getProductLabelName).collect(Collectors.toList())));
                List<ProductLabelResponse> productLabelResponses = new ArrayList<>();
                productLabels.stream().forEach(productLabel ->{
                    ProductLabelResponse productLabelResponse = new ProductLabelResponse();
                    BeanUtils.copyProperties(productLabel,productLabelResponse);
                    productLabelResponses.add(productLabelResponse);
                });
                item.setProductLabels(productLabelResponses);
            }

            item.setGrossProfitRate(grossProfixRate);

            Example example2 = new Example(YxShopProductReceiveRecord.class);
            example2.createCriteria().andEqualTo("productId", item.getId()).andEqualTo("status",1);
            example2.selectProperties("shopId");
            List<YxShopProductReceiveRecord> shopIds = shopProductReceiveRecordMapper.selectByExample(example2);

            if (!CollectionUtils.isEmpty(shopIds)) {
                List<String> productShopIds = shopIds.stream().map(YxShopProductReceiveRecord::getShopId).collect(Collectors.toList());
                StringBuilder shopNames = new StringBuilder("");
                productShopIds.stream().forEach(shopId -> {
                    List<YxShopInfo> matchShopInfos = shopList.stream().filter(shop -> shop.getShopId().equals(shopId)).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(matchShopInfos)) {
                        List<String> names = matchShopInfos.stream().map(YxShopInfo::getName).collect(Collectors.toList());
                        shopNames.append(Joiner.on(",").join(names));
                        shopNames.append(",");
                    }
                });
                item.setShopNames(shopNames.toString());
            }
        });
        handleCategoryInfo(list);
        return CommonPage.restPage(list);
    }

    public static void main(String[] args) {
        List<YxShopInfo> shopList = new ArrayList<>();

    }

    /**
     * 查询三级分类的title
     * @param list
     */
    private void handleCategoryInfo(List<SupplyProductListResponse> list) {
        List<YxProductCategory> categoryList = productCategoryService.selectAll();
        if (CollectionUtils.isEmpty(categoryList)) {
            return;
        }
        list.stream().forEach(item -> {
            categoryList.stream().forEach(category -> {
                if (category.getId().equals(item.getTopCategoryId())) {
                    item.setTopCategoryTitle(category.getTitle());
                    return;
                }
                if (category.getId().equals(item.getCategoryId())) {
                    item.setCategoryTitle(category.getTitle());
                    return;
                }
                if (category.getId().equals(item.getBottomCategoryId())) {
                    item.setBottomCategoryTitle(category.getTitle());
                    return;
                }
            });
        });
    }

    /**
     * 查询商品状态和库存信息
     * @param
     * @param
     * @return
     */
    public CommonResult queryProductStockAndStatus(Integer bankerProductId, Integer supplyId) {
        Example productExample = new Example(YxProduct.class);
        productExample.createCriteria().andEqualTo("bankerProductId",bankerProductId);
        productExample.setOrderByClause("id desc limit 1");
        List<YxProduct> yxProducts = productMapper.selectByExample(productExample);
        if (CollectionUtils.isEmpty(yxProducts)) {
            return CommonResult.failed("商品不存在");
        }
        YxProduct product = yxProducts.get(0);
        //查询冻结的库存
        Example example = new Example(YxStockFrozenRecord.class);
        example.createCriteria().andEqualTo("productId", bankerProductId).andEqualTo("status", StockFrozenRecordStatusEnums.FROZEN_ING.getStatus());
//        Integer productCount = stockFrozenRecordMapper.selectCountByExample(example);
        Integer productCount = 0;
        YxProductSpec productSpec = null;
        if (null != supplyId){
            productSpec = productSpecMapper.selectByPrimaryKey(supplyId);
        }
        Integer productSpecCount = 0;
        if (null != productSpec) {
            Example specExample = new Example(YxStockFrozenRecord.class);
            specExample.createCriteria().andEqualTo("productSpecId", supplyId).andEqualTo("status", StockFrozenRecordStatusEnums.FROZEN_ING.getStatus());
//            productSpecCount = stockFrozenRecordMapper.selectCountByExample(specExample);
        }
        //库存减去冻结中的数量
        ProductStockAndSpecResponse response = ProductStockAndSpecResponse.builder()
                .productId(product.getId())
                .productSpecId(null != productSpec ? productSpec.getId() : null)
                .status(product.getStatus().intValue())
                .stock(null != productSpec ? (productSpec.getStock() - productCount) : null)
                .specStock(null != productSpec ? (productSpec.getStock() - productSpecCount) : null)
                .productName(product.getProductName()).stockWarning(product.getStockWarning())
                .build();
        return CommonResult.success(response);
    }

    /**
     * 查询单个商品状态和总库存
     * @param
     * @return
     */
    public CommonResult queryProductAllStockAndStatus(Integer bankerProductId) {
//        Example productExample = new Example(YxProduct.class);
//        productExample.createCriteria().andEqualTo("bankerProductId",bankerProductId);
        YxProduct product = productMapper.selectByPrimaryKey(bankerProductId);
        if (null == product) {
            return CommonResult.failed("商品不存在");
        }
        Integer productAllSpecStock = productSpecMapper.selectProductAllSpecStock(product.getId());

        //返回商品总库存
        ProductStockAndSpecResponse response = ProductStockAndSpecResponse.builder()
                .productId(product.getId())
                .status(product.getStatus().intValue())
                .stock(productAllSpecStock)
                .build();
        return CommonResult.success(response);
    }

    public List<YxProductSpec> querySupplyProductStockByBankerProductId(Integer bankerProductId) {
        Example productExample = new Example(YxProduct.class);
        productExample.createCriteria().andEqualTo("bankerProductId", bankerProductId);
        productExample.setOrderByClause("id desc limit 1");
        YxProduct product = productMapper.selectOneByExample(productExample);
        if (null == product) {
            return null;
        }
        Example productSpecExample = new Example(YxProductSpec.class);
        productSpecExample.createCriteria().andEqualTo("productId", product.getId());
        List<YxProductSpec> productSpecList = productSpecMapper.selectByExample(productSpecExample);
        return productSpecList;
    }

    public List<YxProductSpec> querySupplyProductStockByBankerProductIds(List<Integer> bankerProductIds) {
        Example productExample = new Example(YxProduct.class);
        productExample.createCriteria().andIn("bankerProductId", bankerProductIds);
        productExample.selectProperties("id");
        List<YxProduct> yxProducts = productMapper.selectByExample(productExample);
        if (CollectionUtils.isEmpty(yxProducts)) {
            return null;
        }
        List<Integer> productIds = yxProducts.stream().map(YxProduct::getId).collect(Collectors.toList());
        Example productSpecExample = new Example(YxProductSpec.class);
        productSpecExample.createCriteria().andIn("productId", productIds);
        return productSpecMapper.selectByExample(productSpecExample);
    }

    /**
     * 更新商品库存
     * @param productId 商品id
     * @param num 更新数量
     * @param type 更新类型 sub-扣减 add-增加
     * @return
     */
    public boolean updateProductStock(Integer productId, Integer num, String type,Integer isZeroProduct) {
        log.info("===updateProductStock request==={}, {}, {}", productId, num, type);
        YxProduct product = productMapper.selectByPrimaryKey(productId);
        if (null == product) {
            log.error("===updateProductStock is fail by product is null==={}, {}", productId, type);
            return false;
        }
        //判断是否0元商品---测评库存
        if (IsZeroProductEnums.IS_ZERO.getCode().equals(isZeroProduct)){
            if ("sub".equals(type)) {
                product.setStockEvaluation(product.getStock() - num);
            }else {
                product.setStockEvaluation(product.getStock() + num);
            }
            if (product.getStockEvaluation().intValue() <= 0) {
                product.setStock(0);
            }
        }else {
            if ("sub".equals(type)) {
                product.setStock(product.getStock() - num);
            }else {
                product.setStock(product.getStock() + num);
            }
            if (product.getStock().intValue() <= 0) {
                product.setStock(0);
            }
        }
        int result = productMapper.updateByPrimaryKeySelective(product);
        return result > 0 ? true : false;
    }

    /**
     * 根据id查询商品详情
     * @param productId
     * @return
     */
    public ProductSelectDetailResponse findProductSelectDetail(Integer productId,Integer platform) {
        log.info("===productId==={}", productId);
        ProductSelectDetailResponse productSelectDetailResponse =productMapper.findProductSelectDetail(productId);
        List<ProductSkuKeyResponse> skuKey = productMapper.findSku(productId);
        List<ProductImgResponse> bannerList = productMapper.findImg(productId, "banner");
        List<ProductImgResponse> infoList = productMapper.findImg(productId, "info");
        List<ProductSpecResponse> spec = productMapper.findSpec(productId);

        Example example = new Example(YxProductLabelProduct.class);
        example.createCriteria().andEqualTo("productId", productSelectDetailResponse.getId());
        List<YxProductLabelProduct> productLabelProducts = productLabelProductMapper.selectByExample(example);
        List<Integer> productLabelIds = productLabelProducts.stream().map(YxProductLabelProduct::getProductLabelId).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(productLabelIds)) {
            Example example1 = new Example(YxProductLabel.class);
            example1.createCriteria().andIn("productLabelId", productLabelIds);
            List<YxProductLabel> productLabels = productLabelMapper.selectByExample(example1);
            productSelectDetailResponse.setLabelNames(Joiner.on(",").join(productLabels.stream().map(YxProductLabel::getProductLabelName).collect(Collectors.toList())));
        }
        FreightTemplateResponse freightTemplateResponse = productMapper.findFreight(productSelectDetailResponse.getFreightId());
        if (null != freightTemplateResponse && null != freightTemplateResponse.getId()){
            List<YxAssignFreight> yxAssignFreightList = freightTemplateDao.queryYxAssignFreightByFreightId(freightTemplateResponse.getId());
            List<YxAssignFreightResponse> yxAssignFreightResponses = new ArrayList<>();
            yxAssignFreightList.stream().forEach(item ->{
                YxAssignFreightResponse yxAssignFreightResponse = new YxAssignFreightResponse();
                BeanUtils.copyProperties(item, yxAssignFreightResponse);
                yxAssignFreightResponses.add(yxAssignFreightResponse);

            });
            freightTemplateResponse.setAssignFreightList(yxAssignFreightResponses);
        }
        productSelectDetailResponse.setFreightTemplateResponse(freightTemplateResponse);
        productSelectDetailResponse.setSkuKey(skuKey);
        productSelectDetailResponse.setBannerList(bannerList);
        productSelectDetailResponse.setInfoList(infoList);
        productSelectDetailResponse.setSpec(spec);

        if (null != platform && 2 == platform ) {
            productSelectDetailResponse.setMinCostPrice("0");
            productSelectDetailResponse.setMaxCostPrice("0");
        }

        return productSelectDetailResponse;
    }


    /**
     * 根据id查询商品详情
     * @param productIds
     * @return
     */
    public List<ProductSelectDetailResponse> findProductSelectDetail(String productIds) {
        log.info("===productId==={}", productIds);
        List<String> idsStr = Arrays.asList(productIds.split(","));
        List<Integer> idsInteger = idsStr.stream().map(Integer::parseInt).collect(Collectors.toList());
        List<ProductSelectDetailResponse> productSelectDetailResponse =productMapper.findProductSelectDetailByIds(idsInteger);
        productSelectDetailResponse.stream().forEach(item -> {
            List<ProductSkuKeyResponse> skuKey = productMapper.findSku(item.getId());
            List<ProductImgResponse> bannerList = productMapper.findImg(item.getId(), "banner");
            List<ProductImgResponse> infoList = productMapper.findImg(item.getId(), "info");
            List<ProductSpecResponse> spec = productMapper.findSpec(item.getId());
            if (null != productSelectDetailResponse) {
                FreightTemplateResponse freightTemplateResponse = productMapper.findFreight(item.getFreightId());
                if (null != freightTemplateResponse && null != freightTemplateResponse.getId()){
                    List<YxAssignFreight> yxAssignFreightList = freightTemplateDao.queryYxAssignFreightByFreightId(freightTemplateResponse.getId());
                    List<YxAssignFreightResponse> yxAssignFreightResponses = new ArrayList<>();
                    yxAssignFreightList.stream().forEach(yxAssignFreight ->{
                        YxAssignFreightResponse yxAssignFreightResponse = new YxAssignFreightResponse();
                        BeanUtils.copyProperties(yxAssignFreight, yxAssignFreightResponse);
                        yxAssignFreightResponses.add(yxAssignFreightResponse);

                    });
                    freightTemplateResponse.setAssignFreightList(yxAssignFreightResponses);
                }
                item.setFreightTemplateResponse(freightTemplateResponse);
            }

            item.setSkuKey(skuKey);
            item.setBannerList(bannerList);
            item.setInfoList(infoList);
            item.setSpec(spec);
        });

        return productSelectDetailResponse;
    }

    /**
     * 根据供应商商品id查询供应链商品详情
     * @param bankerProductIds
     * @return
     */
    public List<ProductSelectDetailResponse> findSupplyChainProductSelectDetail(String bankerProductIds) {
        log.info("===bankerProductIds==={}", bankerProductIds);
        List<String> idsStr = Arrays.asList(bankerProductIds.split(","));
        List<Integer> idsInteger = idsStr.stream().map(Integer::parseInt).collect(Collectors.toList());
        List<ProductSelectDetailResponse> productSelectDetailResponse =productMapper.findProductSelectDetailByBankerProductIds(idsInteger);
        productSelectDetailResponse.stream().forEach(item -> {
            List<ProductSkuKeyResponse> skuKey = productMapper.findSku(item.getId());
            List<ProductImgResponse> bannerList = productMapper.findImg(item.getId(), "banner");
            List<ProductImgResponse> infoList = productMapper.findImg(item.getId(), "info");
            List<ProductSpecResponse> spec = productMapper.findSpec(item.getId());
            if (null != productSelectDetailResponse) {
                FreightTemplateResponse freightTemplateResponse = productMapper.findFreight(item.getFreightId());
                if (null != freightTemplateResponse && null != freightTemplateResponse.getId()){
                    List<YxAssignFreight> yxAssignFreightList = freightTemplateDao.queryYxAssignFreightByFreightId(freightTemplateResponse.getId());
                    List<YxAssignFreightResponse> yxAssignFreightResponses = new ArrayList<>();
                    yxAssignFreightList.stream().forEach(yxAssignFreight ->{
                        YxAssignFreightResponse yxAssignFreightResponse = new YxAssignFreightResponse();
                        BeanUtils.copyProperties(yxAssignFreight, yxAssignFreightResponse);
                        yxAssignFreightResponses.add(yxAssignFreightResponse);

                    });
                    freightTemplateResponse.setAssignFreightList(yxAssignFreightResponses);
                }
                item.setFreightTemplateResponse(freightTemplateResponse);
            }

            item.setSkuKey(skuKey);
            item.setBannerList(bannerList);
            item.setInfoList(infoList);
            item.setSpec(spec);
        });

        return productSelectDetailResponse;
    }

    @Transactional(rollbackFor = Exception.class)
    public void addAndUpdate(ProductRequest productRequest) {
        if(StringUtils.isEmpty(productRequest.getQualityReport())){
            throw new ApiException("商品质检报告为必填项！");
        }
        addAndUpdateLock(productRequest.getProductName());
        parseProductPriceInfo(productRequest);
        //是否新增商品
        boolean isAddProduct = productRequest.getId() == null;

        YxBankerProduct bankerProduct = bankerProductMapper.selectByPrimaryKey(productRequest.getId());
        ProductDto productDto = new ProductDto();
        if (!isAddProduct) {
            BeanUtils.copyProperties(bankerProduct, productDto);
            //保存原有的供应商商品信息 7天
            String bankerProductKey = "bankerProduct:banker_product_key_"+ bankerProduct.getId();
            redisService.set(bankerProductKey,JSONObject.toJSONString(bankerProduct));
            redisService.expire(bankerProductKey,3*24*60*60);
            Example example = new Example(YxBankerProductSpec.class);
            example.createCriteria().andEqualTo("productId",bankerProduct.getId()).andNotEqualTo("status",3);
            List<YxBankerProductSpec> yxBankerProductSpecList = bankerProductSpecMapper.selectByExample(example);
            String bankerProductSpecKey = "bankerProduct:banker_product_spec_key_"+ bankerProduct.getId();
            redisService.set(bankerProductSpecKey, JSONObject.toJSONString(yxBankerProductSpecList));
            redisService.expire(bankerProductSpecKey,3*24*60*60);

        }
        BeanUtils.copyProperties(productRequest, productDto);

        addProductProperty(isAddProduct, productDto, productRequest);

        if (null == productDto.getControlPrice() || 2 == productDto.getControlPrice().intValue()) {
            productDto.setControlReason("");
        }

        //详情图
        if (StringUtils.isEmpty(productDto.getInfoImg())){
            List<ProductImgRequest> infoList = productRequest.getInfoList();
            final String[] infoImg = {""};
            infoList.stream().forEach(item ->{
                String imgUrl = "<img src=\""+item.getImgUrl()+"\">";
                infoImg[0] = infoImg[0] +  imgUrl;
            });
            String infoImgFinal = "<p><br></p><p>" + infoImg[0] + "</p>";
            productDto.setInfoImg(infoImgFinal);
        }

        bankerProductMapper.saveAndUpdate(productDto);
        YxFreightTemplateResponse yxFreightTemplateResponse=freightTemplateDao.selectFreightTemplateResponse(productDto.getFreightId());
        if (null != yxFreightTemplateResponse) {
            Integer zhi=yxFreightTemplateResponse.getQuantify()+1;
            freightTemplateDao.addSYL(zhi,productDto.getFreightId());
        }

        if (!isAddProduct) {
            isUpdateDel(productRequest.getId());
        }

        //保存集采规则
        handleBatchNumInfo(productRequest.getWholesaleNameArr(), productDto.getId());
        saveProductSpecAndSku(productDto, productRequest);

        saveImg(productDto, productRequest);

    }

    /**
     * 保存集采规则信息
     * @param wholesaleNameArr
     * @param productId
     */
    private void handleBatchNumInfo(List<String> wholesaleNameArr, Integer productId) {
        log.info("===handleBatchNumInfo==={}", productId);
        productBatchRuleMapper.updateStatusByProductId(productId);//先逻辑删除已有规则
        if (CollectionUtils.isEmpty(wholesaleNameArr) || null == productId) {
            return;
        }
        wholesaleNameArr.stream().forEach(rule -> {
            String[] values = rule.split("-");
            YxProductBatchRule batchRule = new YxProductBatchRule();
            batchRule.setCreateTime(new Date());
            batchRule.setMax(Integer.parseInt(values[1]));
            batchRule.setMin(Integer.parseInt(values[0]));
            batchRule.setStatus(1);
            batchRule.setProductId(productId);
            productBatchRuleMapper.insertSelective(batchRule);
        });
    }

    private void handleSpecBatchPriceInfo(YxBankerProductSpec spec, Map<String, Object> specRequest, Integer productId) {
        Example example = new Example(YxProductBatchRule.class);
        example.createCriteria().andEqualTo("productId", productId).andEqualTo("status", 1);
        List<YxProductBatchRule> ruleList = productBatchRuleMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(ruleList)) {
            return;
        }
        ruleList.stream().forEach(item -> {
            String key = item.getMin() + "-" + item.getMax();
            Integer price = Integer.parseInt(null == specRequest.get(key) ? "0" : specRequest.get(key).toString());
            if (!StringUtils.isEmpty(price)) {
                YxProductBatchPrice batchPrice = new YxProductBatchPrice();
                batchPrice.setBatchRuleId(item.getId());
                batchPrice.setCreateTime(new Date());
                batchPrice.setPrice(BigDecimal.valueOf(price));
                batchPrice.setSpecId(spec.getId());
                batchPrice.setProductId(productId);
                batchPrice.setStatus(1);
                productBatchPriceMapper.insertSelective(batchPrice);
            }
        });

    }

    private void parseProductPriceInfo(List<ChannelSpecRequest> allList, GoodsRequest goodsRequest) {
        List<ChannelSpecRequest> costPriceList = allList.stream().sorted(Comparator.comparing(ChannelSpecRequest::getCostPrice)).collect(Collectors.toList());//成本价排序
        List<ChannelSpecRequest> supplyPriceList = allList.stream().sorted(Comparator.comparing(ChannelSpecRequest::getSupplyPrice)).collect(Collectors.toList());//供货价排序
        List<ChannelSpecRequest> salePriceList = allList.stream().sorted(Comparator.comparing(ChannelSpecRequest::getSalePrice)).collect(Collectors.toList());//供货价排序
        if (!CollectionUtils.isEmpty(costPriceList)) {
            goodsRequest.setCostPrice(costPriceList.get(0).getCostPrice());
        }
        if (!CollectionUtils.isEmpty(supplyPriceList)) {
            goodsRequest.setSupplyPrice(supplyPriceList.get(0).getSupplyPrice());
        }
        if (!CollectionUtils.isEmpty(salePriceList)) {
            goodsRequest.setSalePrice(salePriceList.get(0).getSalePrice());
        }
    }

    /**
     * 从规格中获取商品成本价、市场价、建议售价
     * @param productRequest
     */
    private void parseProductPriceInfo(ProductRequest productRequest) {
//        List<ProductSpecRequest> specList = productRequest.getSpec();

        List<Map<String, Object>> specList = productRequest.getSpec();
        List<ProductSpecRequest> allList = new ArrayList<>();
        specList.stream().forEach(item -> {
            ProductSpecRequest request = new ProductSpecRequest();
            if (null == item.get("supplyPrice")) {
                item.put("supplyPrice", 0);
            }
            if (null == item.get("updateTime")) {
                item.put("updateTime", System.currentTimeMillis());
            }
            try {
                org.apache.commons.beanutils.BeanUtils.populate(request, item);
                allList.add(request);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        });

        List<ProductSpecRequest> costPriceList = allList.stream().sorted(Comparator.comparing(ProductSpecRequest::getPrice)).collect(Collectors.toList());//成本价排序
        List<ProductSpecRequest> salePriceList = allList.stream().sorted(Comparator.comparing(ProductSpecRequest::getSalePrice)).collect(Collectors.toList());//建议售价排序
        if (!CollectionUtils.isEmpty(costPriceList)) {
            productRequest.setCostPrice(costPriceList.get(0).getPrice());
        }
        if (!CollectionUtils.isEmpty(salePriceList)) {
            productRequest.setSalePrice(salePriceList.get(0).getSalePrice());
        }
    }
    private void parseProductPriceInfo(GoodsRequest productRequest) {
        List<ProductSpecResponse> specList = productRequest.getSpec();
        List<ProductSpecResponse> costPriceList = specList.stream().sorted(Comparator.comparing(ProductSpecResponse::getCostPrice)).collect(Collectors.toList());//成本价排序
        List<ProductSpecResponse> salePriceList = specList.stream().sorted(Comparator.comparing(ProductSpecResponse::getSalePrice)).collect(Collectors.toList());//建议售价排序
        List<ProductSpecResponse> supplyPriceList = new ArrayList<>();
        try {
            supplyPriceList = specList.stream().sorted(Comparator.comparing(ProductSpecResponse::getSupplyPrice)).collect(Collectors.toList());//供货价排序
        } catch (Exception e) {
            log.info("==={}===", e);
            log.info("===供货价为空===");
        }
        if (!CollectionUtils.isEmpty(costPriceList)) {
            productRequest.setCostPrice(costPriceList.get(0).getCostPrice());
        }
        if (!CollectionUtils.isEmpty(salePriceList)) {
            productRequest.setSalePrice(salePriceList.get(0).getSalePrice());
        }
        if (!CollectionUtils.isEmpty(supplyPriceList)) {
            productRequest.setSupplyPrice(supplyPriceList.get(0).getSupplyPrice());
        }
    }

    /**
     * 通知销售端-商品变更
     * @param productId
     * @param productName
     */
    private void callbackByProductEdit(Integer productId, String productName) {
        Example example = new Example(YxShopProductReceiveRecord.class);
        example.createCriteria().andEqualTo("productId", productId).andEqualTo("status", ShopProductReceiveStatusEnums.ACTIVATION.getStatus());
        List<YxShopProductReceiveRecord> list = shopProductReceiveRecordMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        List<String> shopIds = list.stream().map(YxShopProductReceiveRecord::getShopId).collect(Collectors.toList());
        Example example2 = new Example(YxNotifyUrlInfo.class);
        example2.createCriteria().andEqualTo("type", 1).andIn("shopId", shopIds);
        List<YxNotifyUrlInfo> notifyUrlInfos = notifyUrlInfoMapper.selectByExample(example2);
        if (CollectionUtils.isEmpty(notifyUrlInfos)) {
            return;
        }
        notifyUrlInfos.stream().forEach(item -> {
            if ("1".equals(item.getMethodType())) {
                Map<String, String> notifyParam = new HashMap<String, String>();
                notifyParam.put("type", "1");
                notifyParam.put("msg", "供应链商品：" + productName + "，属性发生变更");
                notifyParam.put("productId", String.valueOf(productId));
                String result = HttpClientUtil.doPost(item.getUrl(), notifyParam);
            }
        });

    }

    public void saveImg(ProductDto productDto, ProductRequest productRequest) {
        List<ProductImgRequest> bannerList = productRequest.getBannerList();
        for (ProductImgRequest productImgRequest : bannerList) {
            productImgRequest.setType("banner");
            productImgRequest.setProductId(productDto.getId());
            productImgRequest.setBankerId(productDto.getBankerId());
        }
        List<ProductImgRequest> infoList = productRequest.getInfoList();
        if(!CollectionUtils.isEmpty(infoList)){
            for (ProductImgRequest productImgRequest : infoList) {
                productImgRequest.setType("info");
                productImgRequest.setProductId(productDto.getId());
                productImgRequest.setBankerId(productDto.getBankerId());
            }
        }

        if (!CollectionUtils.isEmpty(infoList)){
            bannerList.addAll(infoList);
        }
        bannerList.stream().forEach(item -> {
            YxBankerProductImg imgBean = new YxBankerProductImg();
            imgBean.setBankerId(item.getBankerId());
            imgBean.setProductId(item.getProductId());
            imgBean.setImgUrl(item.getImgUrl());
            imgBean.setSort(item.getSort());
            imgBean.setType(item.getType());
            imgBean.setCreateTime(new Date());
            bankerProductImgMapper.insert(imgBean);
        });
    }

    /**
     * 保存商品规格 sku
     */
    public void saveProductSpecAndSku(ProductDto productDto, ProductRequest productRequest) {
//        List<ProductSpecRequest> spec = productRequest.getSpec();
        List<Map<String, Object>> spec = productRequest.getSpec();
        //传过来的规格id
//        List<Integer> inputSpecIds = spec.stream().map(ProductSpecRequest::getId).collect(Collectors.toList());
        List<Integer> inputSpecIds = new ArrayList<>();
        spec.stream().forEach(item -> {
            if (null != item.get("id")) {
                inputSpecIds.add(Integer.parseInt(item.get("id").toString()));
            }
        });
        //查到的规格id
        Example example = new Example(YxBankerProductSpec.class);
        example.createCriteria().andEqualTo("productId",productDto.getId()).andNotEqualTo("status",(byte) 3);
        List<YxBankerProductSpec> yxBankerProductSpecs = bankerProductSpecMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(yxBankerProductSpecs)){
            //查到的不存在于传进来的商品规格id
            List<Integer> collect = yxBankerProductSpecs.stream().filter(item -> !inputSpecIds.contains(item.getId())).map(YxBankerProductSpec::getId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)){
                //删除多余的供应商商品规格
//                Example example1 = new Example(YxBankerProductSpec.class);
//                example1.createCriteria().andIn("id",collect);
//                bankerProductSpecMapper.deleteByExample(example1);
                //删除多余的供应商商品规格(逻辑删除)
                collect.stream().forEach(item ->{
                    bankerProductSpecMapper.updateStatusById(item);
                });
            }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        productBatchRuleMapper.updatePrictStatusByProductId(productDto.getId());
        spec.stream().forEach(item -> {
            YxBankerProductSpec bean = new YxBankerProductSpec();
            if (null != item.get("id")) {
                bean = bankerProductSpecMapper.selectByPrimaryKey(Integer.parseInt(item.get("id").toString()));
                bean.setUpdateTime(new Date());
            }else {
                bean = new YxBankerProductSpec();
                bean.setCreateTime(new Date());
            }
            bean.setBankerId(productDto.getBankerId());
            bean.setProductId(productDto.getId());
            bean.setSkuSpec(item.get("skuSpec").toString());
            if (null != item.get("price")) {
                bean.setPrice(BigDecimal.valueOf(Double.valueOf(item.get("price").toString())));
            }else {
                bean.setPrice(BigDecimal.ZERO);
            }
            bean.setSalePrice(BigDecimal.valueOf(Double.valueOf(item.get("salePrice").toString())));
            bean.setProImg(item.get("proImg").toString());
            if (null != item.get("stock")) {
                bean.setStock(Integer.parseInt(item.get("stock").toString()));
            }else {
                bean.setStock(0);
            }
            if (null != item.get("originalPrice")) {
                bean.setOriginalPrice(BigDecimal.valueOf(Double.valueOf(item.get("originalPrice").toString())));
            }else {
                bean.setOriginalPrice(BigDecimal.ZERO);
            }
            if (null != item.get("threeSkuId")) {
                bean.setThreeSkuId(item.get("threeSkuId").toString());
            }
            bean.setStatus(new Byte("1"));
            if (null != item.get("supplyPrice")) {
                bean.setSupplyPrice(BigDecimal.valueOf(Double.valueOf(item.get("supplyPrice").toString())));
            }
            if (null != item.get("goodsCode")) {
                bean.setGoodsCode(item.get("goodsCode").toString());
            }
            if (null != item.get("marketPrice")) {
                bean.setMarketPrice(BigDecimal.valueOf(Double.valueOf(item.get("marketPrice").toString())));
            }else {
                bean.setMarketPrice(BigDecimal.ZERO);
            }
            if (null != bean.getId()) {
                bankerProductSpecMapper.updateByPrimaryKey(bean);
            }else {
                bankerProductSpecMapper.insert(bean);
            }

            handleSpecBatchPriceInfo(bean, item, productDto.getId());
        });

//        spec.stream().forEach(item -> {
//            YxBankerProductSpec bean = new YxBankerProductSpec();
//            if (null != item.getId()) {
//                bean = bankerProductSpecMapper.selectByPrimaryKey(item.getId());
//            }else {
//                bean = new YxBankerProductSpec();
//            }
//            bean.setBankerId(productDto.getBankerId());
//            bean.setProductId(productDto.getId());
//            bean.setSkuSpec(item.getSkuSpec());
//            bean.setPrice(item.getPrice());
//            bean.setSalePrice(item.getSalePrice());
//            bean.setProImg(item.getProImg());
//            bean.setStock(item.getStock());
//            bean.setCreateTime(item.getCreateTime());
//            bean.setUpdateTime(item.getUpdateTime());
//            bean.setOriginalPrice(item.getOriginalPrice());
//            bean.setThreeSkuId(item.getThreeSkuId());
//            bean.setStatus(new Byte("1"));
//            bean.setSupplyPrice(item.getSupplyPrice());
//            bean.setGoodsCode(item.getGoodsCode());
//            if (null != bean.getId()) {
//                bankerProductSpecMapper.updateByPrimaryKey(bean);
//            }else {
//                bankerProductSpecMapper.insert(bean);
//            }
//
//            handleSpecBatchPriceInfo(bean, item, productDto.getId());
//        });


        List<ProductSkuKeyRequest> skuKey = productRequest.getSkuKey();
        for (ProductSkuKeyRequest productSkuKeyRequest : skuKey) {
            productSkuKeyRequest.setPid(productDto.getId());
//            productBankerDao.saveSkuKey(productSkuKeyRequest);
            YxBankerProductSkuKey skuKeyBean = new YxBankerProductSkuKey();
            skuKeyBean.setPid(productSkuKeyRequest.getPid());
            skuKeyBean.setName(productSkuKeyRequest.getName());
            skuKeyBean.setSort(productSkuKeyRequest.getSort());
            skuKeyBean.setCreateTime(new Date());
            bankerProductSkuKeyMapper.insert(skuKeyBean);

            productSkuKeyRequest.getSkuValue().stream().forEach(item -> {
                YxBankerProductSkuValue skuValueBean = new YxBankerProductSkuValue();
                skuValueBean.setPid(productDto.getId());
                skuValueBean.setKid(skuKeyBean.getId());
                skuValueBean.setValue(item.getValue());
                skuValueBean.setCreateTime(new Date());
                skuValueBean.setStatus(new Byte("1"));
                bankerProductSkuValueMapper.insert(skuValueBean);
            });
//            productBankerDao.saveSkuValue(productDto.getId(), productSkuKeyRequest.getId(), productSkuKeyRequest.getSkuValue());
        }
    }

    /**
     * 更新商品时 删除sku  spec 信息
     */
    public void isUpdateDel(Integer productId) {
        Example example1 = new Example(YxBankerProductSkuKey.class);
        example1.createCriteria().andEqualTo("pid", productId);
        bankerProductSkuKeyMapper.deleteByExample(example1);

        Example example2 = new Example(YxBankerProductSkuValue.class);
        example2.createCriteria().andEqualTo("pid", productId);
        bankerProductSkuValueMapper.deleteByExample(example2);

//        Example example3 = new Example(YxBankerProductSpec.class);
//        example3.createCriteria().andEqualTo("productId", productId);
//        bankerProductSpecMapper.deleteByExample(example3);

        Example example4 = new Example(YxBankerProductImg.class);
        example4.createCriteria().andEqualTo("productId", productId);
        bankerProductImgMapper.deleteByExample(example4);
    }

    /**
     * 新增修改商品 补全属性
     *
     * @param isAddProduct
     * @param productDto
     * @param productRequest
     */
    public void addProductProperty(boolean isAddProduct, ProductDto productDto, ProductRequest productRequest) {
        List<Map<String, Object>> specMap = productRequest.getSpec();
        AtomicReference<Integer> stock = new AtomicReference<>(0);
        specMap.stream().forEach(item -> {
            stock.set(stock.get() + Integer.parseInt(item.get("stock").toString()));
        });
        productDto.setStock(stock.get());
//        productDto.setStock(productRequest.getSpec().stream().mapToInt(ProductSpecRequest::getStock).sum());

        productDto.setWarehouse(productDto.getProductName());

        String specJson = this.getSpecJson(productRequest.getSkuKey());
        productDto.setAttributeJson(specJson);

        if (isAddProduct) {
            YxBanker bankerInfo = bankerService.getUserInfo();
            productDto.setBankerId(bankerInfo.getId());
            productDto.setBankerName(bankerInfo.getName());
            productDto.setWarehouseName(bankerInfo.getName());
            productDto.setProductNo(OrderUtils.getProductNo());
        }
    }

    /**
     * 获取规格JSON
     *
     * @param skuKey
     * @return
     */
    public String getSpecJson(List<ProductSkuKeyRequest> skuKey) {
        List<Map<String, Object>> specList = new ArrayList<>();
        for (ProductSkuKeyRequest productSkuKeyRequest : skuKey) {
            List<String> collect = productSkuKeyRequest.getSkuValue().stream().map(ProductSkuValueRequest::getValue).collect(Collectors.toList());
            Map<String, Object> map = new HashMap<>();
            map.put("spanName", productSkuKeyRequest.getName());
            map.put("spanValue", collect);
            specList.add(map);
        }
        return JSON.toJSONString(specList);
    }

    /**
     * 防止重复提交锁
     *
     * @param productName
     */
    public void addAndUpdateLock(String productName) {
        // 获取锁
        RLock lock = redissonClient.getLock(RedisConstants.BANKER_PRODUCT + productName);
        boolean b = false;
        try {
            b = lock.tryLock(0, 5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            lock.unlock();
            throw new ApiException(ResultCode.FAILED);
        }
        if (!b) {
            throw new ApiException(ResultCode.EXE_FAILED);
        }
    }

    public ProductDataResponse getProductInfo(Integer productId) {
        YxBanker userInfo = bankerService.getUserInfo();
        ProductDataResponse productResponse = bankerProductMapper.findInfoById(productId);
        if (!userInfo.getId().equals(productResponse.getBankerId())) {
            log.warn("userInfo.id={}, bankerId={}", userInfo.getId(), productResponse.getBankerId());
            throw new ApiException("参数错误！");
        }
        List<ProductSkuKeyRequest> skuKey = bankerProductSkuKeyMapper.findSku(productId);

        Example example = new Example(YxBankerProductImg.class);
        example.createCriteria().andEqualTo("productId", productId).andIn("type", Arrays.asList("banner", "info"));
        example.orderBy("sort").asc();
        List<YxBankerProductImg> productImgList = bankerProductImgMapper.selectByExample(example);


        List<ProductImgRequest> bannerList = new ArrayList<>();
        List<ProductImgRequest> infoList = new ArrayList<>();
        productImgList.stream().forEach(item -> {
            if (item.getType().equals("banner")) {
                ProductImgRequest request = new ProductImgRequest();
                BeanUtils.copyProperties(item, request);
                bannerList.add(request);
            }
            if (item.getType().equals("info")) {
                ProductImgRequest request = new ProductImgRequest();
                BeanUtils.copyProperties(item, request);
                infoList.add(request);
            }
        });

        Example specExample = new Example(YxBankerProductSpec.class);
        specExample.createCriteria().andEqualTo("productId", productId).andEqualTo("status",1);
        List<YxBankerProductSpec> specList = bankerProductSpecMapper.selectByExample(specExample);
//        List<ProductSpecRequest> spec = new ArrayList<>();
//        specList.stream().forEach(item -> {
//            ProductSpecRequest request = new ProductSpecRequest();
//            BeanUtils.copyProperties(item, request);
//            spec.add(request);
//        });
        List<Map<String, Object>> spec = new ArrayList<>();
        specList.stream().forEach(item -> {
            Map<String, Object> specMap = new HashMap();
            BeanMap beanMap = BeanMap.create(item);
            for (Object key : beanMap.keySet()) {
                specMap.put(key + "", beanMap.get(key));
            }
            Example batchPriceExample = new Example(YxProductBatchPrice.class);
            batchPriceExample.createCriteria().andEqualTo("productId", productId).andEqualTo("specId", item.getId()).andEqualTo("status", 1);
            List<YxProductBatchPrice> batchPriceList = productBatchPriceMapper.selectByExample(batchPriceExample);
            List<Integer> batchRuleIds = null;
            if (!CollectionUtils.isEmpty(batchPriceList)) {
                batchRuleIds = batchPriceList.stream().map(YxProductBatchPrice::getBatchRuleId).collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(batchRuleIds)) {
                Example batchRuleExample = new Example(YxProductBatchRule.class);
                batchRuleExample.createCriteria().andIn("id", batchRuleIds);
                List<YxProductBatchRule> batchRuleList = productBatchRuleMapper.selectByExample(batchRuleExample);
                if (!CollectionUtils.isEmpty(batchRuleList)) {
                    batchRuleList.stream().forEach(rule -> {
                        String ruleKey = rule.getMin() + "-" + rule.getMax();
                        List<YxProductBatchPrice> matchPriceList = batchPriceList.stream().filter(batchPrice -> batchPrice.getBatchRuleId().equals(rule.getId())).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(matchPriceList)) {
                            specMap.put(ruleKey, matchPriceList.get(0).getPrice());
                        }
                    });
                }
            }
            spec.add(specMap);
        });

        productResponse.setSkuKey(skuKey);
        productResponse.setBannerList(bannerList);
        productResponse.setInfoList(infoList);
        productResponse.setSpec(spec);
        // 质检报告--数组形式
        if (productResponse != null) {
            String reportList = productResponse.getQualityReport();
            List<ProductReportRequest> list = new ArrayList<>();
            if (reportList != null && reportList != "") {
                String[] reportArray = reportList.split(",");
                for (String string : reportArray) {
                    ProductReportRequest prr = new ProductReportRequest();
                    prr.setReportImg(string);
                    list.add(prr);
                }
                productResponse.setReportArray(list);
            }
        }
        Example batchNumExample = new Example(YxProductBatchRule.class);
        batchNumExample.createCriteria().andEqualTo("productId", productId).andEqualTo("status", 1);
        List<YxProductBatchRule> batchRuleList = productBatchRuleMapper.selectByExample(batchNumExample);
        List<String> wholesaleNameArr = new ArrayList<>();
        if (!CollectionUtils.isEmpty(batchRuleList)) {
            batchRuleList.stream().forEach(item -> {
                String ruleKey = item.getMin() + "-" + item.getMax();
                wholesaleNameArr.add(ruleKey);
            });
        }
        productResponse.setWholesaleNameArr(wholesaleNameArr);
        return productResponse;
    }

    public List<CategoryRedefineResponse> queryCategoryListByTitle(String title) {
        List<YxProductCategory> categoryList = productCategoryService.queryByTitle(title);

        List<CategoryResponse> list = new ArrayList<>();
        categoryList.stream().forEach(item -> {
            CategoryResponse response = new CategoryResponse();
            BeanUtils.copyProperties(item, response);
            list.add(response);
        });
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<CategoryRedefineResponse> result = new LinkedList<>();
        AtomicInteger id = new AtomicInteger(1);
        list.stream().forEach(item -> {
            if (item.getLevel() != null && item.getLevel().equals(3)) {
//                parseLevelByThree(item, result);
                parseResult(item, result, 3, id.get());
            }else if (item.getLevel() != null && item.getLevel().equals(2)) {
//                parseLevelByTwo(item, result);
                parseResult(item, result, 2, id.get());
            }else if (item.getLevel() != null && item.getLevel().equals(1)) {
//                parseLevelByOne(item, result);
                parseResult(item, result, 1, id.get());
            }
            id.addAndGet(1);
        });

        return result;
    }

    private void parseResult(CategoryResponse item, List<CategoryRedefineResponse> result, Integer level, Integer id) {
        CategoryRedefineResponse response = new CategoryRedefineResponse();
        response.setId(id);
        CategoryResponse two = null;
        CategoryResponse one = null;
        switch (level) {
            case 1:
                response.setTopId(item.getId());
                response.setTopTitle(item.getTitle());
                break;
            case 2:
                one = new CategoryResponse();
                response.setSecondId(item.getId());
                response.setSecondTitle(item.getTitle());
                YxProductCategory oneCategory = productCategoryService.queryById(item.getPid());
                if (null != oneCategory) {
                    BeanUtils.copyProperties(oneCategory, one);
                }
                response.setTopId(one.getId());
                response.setTopTitle(one.getTitle());
                customerEquals(result, response, 1);
                break;
            case 3:
                response.setLastId(item.getId());
                response.setLastTitle(item.getTitle());
                YxProductCategory twoCategory = productCategoryService.queryById(item.getPid());
                if (null == twoCategory) {
                    break;
                }
                two = new CategoryResponse();
                BeanUtils.copyProperties(twoCategory, two);
                response.setSecondId(two.getId());
                response.setSecondTitle(two.getTitle());
                YxProductCategory oneCategory2 = productCategoryService.queryById(two.getPid());
                if (null == oneCategory2) {
                    break;
                }
                one = new CategoryResponse();
                BeanUtils.copyProperties(oneCategory2, one);
                response.setTopId(one.getId());
                response.setTopTitle(one.getTitle());
                customerEquals(result, response, 2);
                break;
        }
        if (null != response) {
            result.add(response);
        }
    }

    private boolean customerEquals(List<CategoryRedefineResponse> obj1, CategoryRedefineResponse obj2, Integer level) {
        if (CollectionUtils.isEmpty(obj1) || obj2 == null) {
            return false;
        }
        AtomicBoolean result = new AtomicBoolean(false);

        Iterator iterator = obj1.iterator();
        while (iterator.hasNext()) {
            CategoryRedefineResponse cur = (CategoryRedefineResponse) iterator.next();
            if(level == 1 && obj2.getTopId().equals(cur.getTopId()) && null == cur.getSecondId()){
                iterator.remove();
            }
            if (level == 2 && obj2.getTopId().equals(cur.getTopId()) && obj2.getSecondId().equals(cur.getSecondId()) && null == cur.getLastId()) {
                iterator.remove();
            }
        }
        return result.get();
    }

    public void synriBankerProductInfo(Integer bankerProductId) {
        try {
//            Example example = new Example(YxProduct.class);
//            example.createCriteria().andEqualTo("bankerProductId", bankerProductId);
            YxProduct product = productMapper.selectByPrimaryKey(bankerProductId);
            //查询供应商商品信息
            YxBankerProduct bankerProduct = bankerProductMapper.selectByPrimaryKey(product.getBankerProductId());
            //同步内容
            bankerProduct.setProductName(product.getProductName());//商品名称
            bankerProduct.setTopCategoryId(product.getTopCategoryId());//一级分类
            bankerProduct.setCategoryId(product.getCategoryId());//二级分类
            bankerProduct.setBottomCategoryId(product.getBottomCategoryId());//三级分类
            bankerProduct.setDescr(product.getDescr());//商品介绍
            bankerProduct.setCostPrice(product.getCostPrice());//成本价
            bankerProduct.setProductImg(product.getProductImg());//商品主图
            bankerProduct.setSceneImg(product.getSceneImg());//场景图
            bankerProduct.setStatus((byte) 2);//产品状态
            bankerProduct.setAuditStatus(2);//审核状态
            bankerProduct.setShrinkImg(product.getShrinkImg());//缩列图
            bankerProduct.setStockEvaluation(product.getStockEvaluation());//测评库存
            bankerProduct.setRate(product.getRate());//费率
            bankerProduct.setRecDescr(product.getRecDescr());//推荐描述

            bankerProductMapper.updateByPrimaryKey(bankerProduct);

//            List<ProductImgResponse> bannerList = productImgMapper.findImg(product.getId(), "banner");//商品详情图
//            List<ProductImgResponse> infoList = goodsDao.findImg(product.getId(), "info");//轮循图
//            saveImg(bankerProduct.getId(),bankerProduct.getBankerId(),bannerList,infoList);
        } catch (Exception e) {
            log.error("打回后同步商品信息异常{}", e);
        }
    }

//    @Transactional(rollbackFor = Exception.class)
    public void updateGoods(GoodsRequest goodsRequest) {

        //修改前保存原来信息
        YxProduct product = productMapper.selectByPrimaryKey(goodsRequest.getId());
        if (null != product){
            YxBankerProduct bankerProduct = bankerProductMapper.selectByPrimaryKey(product.getBankerProductId());
            product.setControlPrice(bankerProduct.getControlPrice());
            product.setAddressId(bankerProduct.getAddressId());
            product.setFreightId(bankerProduct.getFreightId());
            String productMsg = JSONObject.toJSONString(product);
            Map<String,String> map = new HashMap<>();
            map.put("product", productMsg);
            Example example = new Example(YxProductSpec.class);
            example.createCriteria().andEqualTo("productId",goodsRequest.getId());
            List<YxProductSpec> yxProductSpecs = productSpecMapper.selectByExample(example);
            map.put("productSpecList",JSONObject.toJSONString(yxProductSpecs));
            redisService.set("product:supply_chain_product_key_" + goodsRequest.getId(),JSONObject.toJSONString(map));
            redisService.expire("product:supply_chain_product_key_"+goodsRequest.getId(),60 * 30);
        }


        productMapper.deleteImg(goodsRequest.getId());
        List<ProductImgResponse> bannerList = goodsRequest.getBannerList();
        for (ProductImgResponse productImgRequest : bannerList) {
            if (productImgRequest.getSort() == null) {
                throw new ApiException("商品轮播图-图片排序值不能为空！");
            }
            productImgRequest.setType("banner");
            productImgRequest.setProductId(goodsRequest.getId());
        }
        List<ProductImgResponse> infoList = goodsRequest.getInfoList();
        if (!CollectionUtils.isEmpty(infoList)){
            for (ProductImgResponse productImgRequest : infoList) {
                if (productImgRequest.getSort() == null) {
                    throw new ApiException("商品主图-图片排序值不能为空！");
                }
                productImgRequest.setType("info");
                productImgRequest.setProductId(goodsRequest.getId());
            }
            bannerList.addAll(infoList);
        }
        productMapper.saveImg(bannerList);
        //更新供应商商品图
        //删除旧图
        bankerProductImgMapper.deleteByProductId(product.getBankerProductId());
        bannerList.forEach(e -> {
            e.setProductId(product.getBankerProductId());
            e.setBankerId(goodsRequest.getBankerId());
        });
        //保存供应链修改的商品图
        bankerProductImgMapper.saveImg(bannerList);
        try {
            //通知商品变更到销售端
            checkUpdateProductType(goodsRequest);
        } catch (Exception e) {
            log.info("===通知商品属性变更异常==={}, {}", goodsRequest.getId(), goodsRequest.getProductName());
            log.error("===通知商品属性变更异常:{}==={}", goodsRequest.getId(), e);
        }
        List<Integer> collect = new ArrayList<>();
        if (null != goodsRequest.getSpecArr()) {
            List<Integer> finalCollect = collect;
            goodsRequest.getSpecArr().stream().forEach(specMap -> {
                if (null != specMap.get("supplyId")) {
                    finalCollect.add(Integer.parseInt(specMap.get("supplyId").toString()));
                }
            });
            collect = finalCollect;
        }else if (null != goodsRequest.getSpec()){
            collect = goodsRequest.getSpec().stream().filter(item -> null != item.getSupplyId()).map(ProductSpecResponse::getSupplyId).collect(Collectors.toList());
        }
        Example example = new Example(YxBankerProductSpec.class);
        example.createCriteria().andIn("id",collect);
        List<YxBankerProductSpec> yxBankerProductSpecs = bankerProductSpecMapper.selectByExample(example);
        Integer stockSum = 0;
        //更新规格相关信息
        if (goodsRequest.getSpec().size() > 0) {
            List<ChannelSpecRequest> channelSpecRequestList = new ArrayList<>();
            for (Map<String, Object> productSpecResponseMap : goodsRequest.getSpecArr()) {
                log.info("===productSpecResponseMap:{}", productSpecResponseMap);
                if (null != productSpecResponseMap.get("costPrice") && null != productSpecResponseMap.get("id")) {
                    Double costPriceNew = Double.valueOf(productSpecResponseMap.get("costPrice").toString());
                    YxProductSpec productSpec = productSpecMapper.selectByPrimaryKey(Integer.parseInt(productSpecResponseMap.get("id").toString()));
                    log.info("===cost1:{}, cost2:{}", productSpec.getCostPrice(), costPriceNew);
                    if (productSpec.getCostPrice().compareTo(BigDecimal.valueOf(costPriceNew)) < 0 && risePriceSwitch != 1) {
                        throw new ApiException("规格成本价不能大于当前成本价！");
                    }
                }
                ProductSpecResponse productSpecResponse = new ProductSpecResponse();
                productSpecResponse.setId(Integer.parseInt(productSpecResponseMap.get("id").toString()));
                if (null != productSpecResponseMap.get("supplyPrice")) {
                    productSpecResponse.setSupplyPrice(BigDecimal.valueOf(Double.valueOf(productSpecResponseMap.get("supplyPrice").toString())));
                }else {
                    productSpecResponse.setSupplyPrice(BigDecimal.ZERO);
                }
                if (null != productSpecResponseMap.get("costPrice")) {
                    productSpecResponse.setCostPrice(BigDecimal.valueOf(Double.valueOf(productSpecResponseMap.get("costPrice").toString())));
                }else {
                    productSpecResponse.setCostPrice(BigDecimal.ZERO);
                }
                if (null != productSpecResponseMap.get("salePrice")) {
                    productSpecResponse.setSalePrice(BigDecimal.valueOf(Double.valueOf(productSpecResponseMap.get("salePrice").toString())));
                }else {
                    productSpecResponse.setSalePrice(BigDecimal.ZERO);
                }
                if (null != productSpecResponseMap.get("curPrice")) {
                    productSpecResponse.setCurPrice(BigDecimal.valueOf(Double.valueOf(productSpecResponseMap.get("curPrice").toString())));
                }
                if (null != productSpecResponseMap.get("price")) {
                    productSpecResponse.setPrice(BigDecimal.valueOf(Double.valueOf(productSpecResponseMap.get("price").toString())));
                }
                if (null != productSpecResponseMap.get("goodsCode")) {
                    productSpecResponse.setGoodsCode(productSpecResponseMap.get("goodsCode").toString());
                }
                productSpecResponse.setStock(Integer.parseInt(productSpecResponseMap.get("stock").toString()));
                productSpecResponse.setProImg(productSpecResponseMap.get("proImg").toString());
                if (null != productSpecResponseMap.get("supplyId")) {
                    productSpecResponse.setSupplyId(Integer.parseInt(productSpecResponseMap.get("supplyId").toString()));
                }
                //调用销售端接口请求的参数
                ChannelSpecRequest channelSpecRequest = new ChannelSpecRequest();
                channelSpecRequest.setSupplyId(productSpecResponse.getId());
                channelSpecRequest.setSupplyPrice(productSpecResponse.getSupplyPrice());
                channelSpecRequest.setCostPrice(productSpecResponse.getCostPrice());
                channelSpecRequest.setSalePrice(productSpecResponse.getSalePrice());
                channelSpecRequestList.add(channelSpecRequest);

                stockSum = stockSum + productSpecResponse.getStock();
                log.info("===update_product_spec_app==={}", productSpecResponse);
                productSpecResponse.setProductId(goodsRequest.getId());
                if (null != productSpecResponse.getId()) {
                    productMapper.updateSpecInfoApp(productSpecResponse);
                }
                if (!CollectionUtils.isEmpty(yxBankerProductSpecs)) {
                    //同步更新供应商库存
                    List<YxBankerProductSpec> collect1 = yxBankerProductSpecs.stream().filter(item -> item.getId().equals(productSpecResponse.getSupplyId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collect1)) {
                        YxBankerProductSpec yxBankerProductSpec = collect1.get(0);
                        bankerProductSpecMapper.updateStockById(yxBankerProductSpec.getId(), productSpecResponse.getStock(), productSpecResponse.getCostPrice(),productSpecResponseMap.get("proImg").toString());
                    }
                }
            }
            //同步更新销售端规格供货价
            syncSupplyPrice(channelSpecRequestList);
            //取成本价、供货价和建议售价的最小值赋值给商品
            parseProductPriceInfo(channelSpecRequestList, goodsRequest);
        }
//        parseProductPriceInfo(goodsRequest);
        //修改商品信息
        goodsRequest.setStock(stockSum);
        productMapper.updateGoodsNew(goodsRequest);
        //更新供应商商品信息
        updateBankerProduct(goodsRequest);
        //更新销售端商品信息
        goodsRequest.setSupplyProductId(goodsRequest.getId());
        syncChannelProductMsg(goodsRequest);

        try {
            //对比更新的信息
            checkProductMsgBySupply(goodsRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 同步更新销售端规格供货价
     */
    public void syncSupplyPrice(List<ChannelSpecRequest> channelSpecRequestList) {
        Example notifyUrlInfoexample = new Example(YxNotifyUrlInfo.class);
        notifyUrlInfoexample.createCriteria().andEqualTo("type", 4);
        List<YxNotifyUrlInfo> notifyUrlInfos = notifyUrlInfoMapper.selectByExample(notifyUrlInfoexample);
        log.info("======同步更新销售端规格供货价======notifyUrlInfos={}", notifyUrlInfos);
        if (!CollectionUtils.isEmpty(notifyUrlInfos)) {
            notifyUrlInfos.stream().forEach(item -> {
                log.info("======同步更新销售端规格供货价====参数==={},{}", channelSpecRequestList, item.getUrl());
                String s = HttpClientUtil.doPostJson(item.getUrl(), JSONObject.toJSONString(channelSpecRequestList));
                log.info("======同步更新销售端规格供货价====返回==={}", s);
            });
        }
    }
    /**
     * 同步更新销售端商品信息
     */
    public void syncChannelProductMsg(GoodsRequest goodsRequest) {
        Example notifyUrlInfoexample = new Example(YxNotifyUrlInfo.class);
        notifyUrlInfoexample.createCriteria().andEqualTo("type", 5);
        List<YxNotifyUrlInfo> notifyUrlInfos = notifyUrlInfoMapper.selectByExample(notifyUrlInfoexample);
        log.info("======同步更新销售端商品信息======notifyUrlInfos={}", notifyUrlInfos);
        if (!CollectionUtils.isEmpty(notifyUrlInfos)) {
            notifyUrlInfos.stream().forEach(item -> {
                log.info("======同步更新销售端商品信息====参数==={},{}", goodsRequest, item.getUrl());
                String s = HttpClientUtil.doPostJson(item.getUrl(), JSONObject.toJSONString(goodsRequest));
                log.info("======同步更新销售端商品信息====返回==={}", s);
            });
        }
    }

    /**
     * 检查变更供应链商品类型
     * @return type：0-没有改变（这里只校验规格和供货价的变化） 1-规格变动 2-供货价变动 3-规格和供货价均有变动
     */
    private Integer checkUpdateProductType(GoodsRequest goodsRequest) {
        log.info("===checkUpdateProductType===");
        AtomicReference<Integer> type = new AtomicReference<>(0);
        Integer productId = goodsRequest.getId();
        Example example = new Example(YxProductSpec.class);
        example.createCriteria().andEqualTo("productId", productId);
        List<YxProductSpec> productSpecList = productSpecMapper.selectByExample(example);
        log.info("===size is equals==={},{}", productSpecList.size(), goodsRequest.getSpec().size());
        if (productSpecList.size() != goodsRequest.getSpec().size()) {
            type.set(1);
        }
        log.info("===type1==={}", type);
        Integer finalType = type.get();
        productSpecList.stream().forEach(item -> {
            List<ProductSpecResponse> matchList = goodsRequest.getSpec().stream().filter(s -> s.getId().equals(item.getId())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(matchList)) {
                return;
            }
            log.info("===matchList===");
            log.info("==={},{}===", item.getSupplyPrice(), matchList.get(0).getSupplyPrice());
            if (null != item.getSupplyPrice()){
                item.setSupplyPrice(BigDecimal.ZERO);
            }
            if (null != item.getSupplyPrice() && !item.getSupplyPrice().equals(matchList.get(0).getSupplyPrice())) {
                if (finalType == 1) {
                    type.set(3);
                }else {
                    type.set(2);
                }
                return;
            }
//            goodsRequest.getSpec().stream().forEach(reqSpec -> {
//                if (item.getId().equals(reqSpec.getId()) && null != item.getSupplyPrice() && item.getSupplyPrice().equals(reqSpec.getSupplyPrice())) {
//                    if (finalType == 1) {
//                        type.set(3);
//                    }else {
//                        type.set(2);
//                    }
//                    return;
//                }
//            });
        });
        log.info("===type2==={}", type);
        String productName = goodsRequest.getProductName();
        String message = "";
        if (type.get().equals(1)) {
            message = "供应链商品：" + productName + "，规格发生变化，请及时处理！";
        }else if (type.get().equals(2)) {
            message = "供应链商品：" + productName + "，规格供货价发生变化，请及时处理！";
        }else if (type.get().equals(3)) {
            message = "供应链商品：" + productName + "，规格和供货价均发生变化，请及时处理！";
        }
        if (!StringUtils.isEmpty(message)) {
            sendMessageToShopClient(productName, productId, message);
        }
        return type.get();
    }

    /**
     * 发送通知到销售端
     * @param productName
     * @param productId
     * @param message
     */
    private void sendMessageToShopClient(String productName, Integer productId, String message) {
        log.info("===sendMessageToShopClient productId==={}", productId);
        Example example = new Example(YxShopProductReceiveRecord.class);
        example.createCriteria().andEqualTo("productId", productId).andEqualTo("status", ShopProductReceiveStatusEnums.ACTIVATION.getStatus());
        List<YxShopProductReceiveRecord> list = shopProductReceiveRecordMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        log.info("===sendMessageToShopClient===");
        List<String> shopIds = list.stream().map(YxShopProductReceiveRecord::getShopId).collect(Collectors.toList());
        log.info("===shopIds==={}", JSONObject.toJSONString(shopIds));
        Example example2 = new Example(YxNotifyUrlInfo.class);
        example2.createCriteria().andEqualTo("type", 1).andIn("shopId", shopIds);
        List<YxNotifyUrlInfo> notifyUrlInfos = notifyUrlInfoMapper.selectByExample(example2);
        if (CollectionUtils.isEmpty(notifyUrlInfos)) {
            return;
        }
        notifyUrlInfos.stream().forEach(item -> {
            if ("1".equals(item.getMethodType())) {
                log.info("===url==={}", item.getUrl());
                Map<String, String> notifyParam = new HashMap<String, String>();
                notifyParam.put("type", "1");
                notifyParam.put("msg", message);
                notifyParam.put("productId", String.valueOf(productId));
                String result = HttpClientUtil.doPostJson(item.getUrl(), JSONObject.toJSONString(notifyParam));
            }
        });

    }

    //下架销售端商品
    public void downShopProduct(String bankerProductIds,String outOfSelection) {
        log.info("===下架销售端商品==={}", bankerProductIds);
        if (StringUtils.isEmpty(bankerProductIds)) {
            log.info("===bankerProductIds is null===");
            return;
        }
        Example example = new Example(YxNotifyUrlInfo.class);
        example.createCriteria().andEqualTo("type", 2);
        List<YxNotifyUrlInfo> notifyUrlInfos = notifyUrlInfoMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(notifyUrlInfos)) {
            return;
        }
        notifyUrlInfos.stream().forEach(item -> {
            Map<String, String> params = new HashMap<>();
            params.put("bankerProductIds", bankerProductIds);
            params.put("outOfSelection", outOfSelection);
            try {
                String result = HttpClientUtil.doGet(item.getUrl(), params);
                log.info("===downShopProduct result==={},{}", result, item.getUrl());
            } catch (Exception e) {
                log.error("===downShopProduct is error==={}",item.getUrl());
                log.error("==={}", e);
            }
        });
    }

    private void updateBankerProduct(GoodsRequest goodsRequest) {
        YxProduct product = productMapper.selectByPrimaryKey(goodsRequest.getId());
        Integer bankerProductId = product.getBankerProductId();
        YxBankerProduct bankerProduct = bankerProductMapper.selectByPrimaryKey(bankerProductId);
        bankerProduct.setControlPrice(goodsRequest.getControlPrice());
        if (null != goodsRequest.getControlPrice() && goodsRequest.getControlPrice().equals(0)) {
            goodsRequest.setControlReason("");
        }
        bankerProduct.setControlReason(goodsRequest.getControlReason());
        bankerProduct.setAddressId(goodsRequest.getAddressId());
        bankerProduct.setBrandId(goodsRequest.getBrandId());
        bankerProduct.setBrand(goodsRequest.getBrand());
        bankerProduct.setFreightId(goodsRequest.getFreightId());
        bankerProduct.setTopCategoryId(goodsRequest.getTopCategoryId());
        bankerProduct.setCategoryId(goodsRequest.getCategoryId());
        bankerProduct.setBottomCategoryId(goodsRequest.getBottomCategoryId());
        bankerProduct.setProductName(goodsRequest.getProductName());
        bankerProduct.setDescr(goodsRequest.getDescr());
        bankerProduct.setProductImg(goodsRequest.getProductImg());
        bankerProductMapper.updateByPrimaryKey(bankerProduct);
    }

    /**
     * 商品审核
     * @param product
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer syncBankerToProduct(ProductCheckRequest product) {

        Integer isExists = productMapper.isExists(product.getId());
        if(isExists > 0) {
            throw new ApiException("该供应商商品已审核通过，暂不支持重复审核！");
        }
        YxBankerProduct bankerProduct = bankerProductMapper.selectByPrimaryKey(product.getId());
        //商品分类同步到供应商商品
        productMapper.updateCategoryId(product.getId(),product.getTopCategoryId(),product.getCategoryId(),product.getBottomCategoryId(),product.getAppraisalType());
        // 1.供应商产品-->普通产品库
        // 商品审核通过 状态为：待上架
//        product.setBankerProductId(product.getId());
//        product.setAuditStatus(1);
        // 审核时不是0元测评商品时，isZeroProduct改为0-否
        YxProduct insertProduct = new YxProduct();
        BeanUtils.copyProperties(product, insertProduct);
        insertProduct.setBankerProductId(product.getId());
        insertProduct.setBrand(bankerProduct.getBrand());

        Example example = new Example(YxProduct.class);
        example.createCriteria().andEqualTo("bankerProductId", product.getId());
        List<YxProduct> existList = productMapper.selectByExample(example);

        log.info("===商品审核时，供应链是否存在供应商的商品==={},{}", product.getId(), CollectionUtils.isEmpty(existList));
        if (!CollectionUtils.isEmpty(existList)) {
            insertProduct.setId(existList.get(0).getId());
        }else {
            insertProduct.setId(null);
        }
        // 审核通过 把商品名称赋值给长标题
        insertProduct.setLongTitle(product.getProductName());
        insertProduct.setBrandId(null);
        insertProduct.setStatus((byte) 4);
        insertProduct.setBrandId(bankerProduct.getBrandId());
        insertProduct.setTypeno(bankerProduct.getTypeno());
        insertProduct.setCountryCode(bankerProduct.getCountryCode());
        insertProduct.setUnitCode(bankerProduct.getUnitCode());
        insertProduct.setConsolidatedTaxRate(bankerProduct.getConsolidatedTaxRate());
        Integer insertCount = 0;
        Integer updateCount = 0;
        if (null == insertProduct.getId()) {
            insertProduct.setCreateTime(new Date());
            //费率
            insertProduct.setRate(BigDecimal.valueOf(1));
            if (com.alibaba.excel.util.StringUtils.isEmpty(insertProduct.getRecDescr())){
                //推荐描述
                insertProduct.setRecDescr(insertProduct.getDescr());
            }
            insertProduct.setRecDescr(null);
            insertProduct.setAppraisalType(null == product.getAppraisalType() ? 1 : product.getAppraisalType());
            insertCount = productMapper.insertSelective(insertProduct);
        }else {
            if (null == insertProduct.getBrandId()){
                insertProduct.setBrandId(0);
            }
            insertProduct.setRecDescr(null);
            insertProduct.setUpdateTime(new Date());
            updateCount = productMapper.updateByPrimaryKeySelective(insertProduct);
        }

        //主键自增拿到增加后的productId
        Integer productId = insertProduct.getId();

        // 2.同步商品img
        if (updateCount > 0){
            productImgMapper.deleteByProductId(productId);
        }
        Example example2 = new Example(YxBankerProductImg.class);
        example2.createCriteria().andEqualTo("productId", product.getId());
        List<YxBankerProductImg> bpImgList = bankerProductImgMapper.selectByExample(example2);
        if(!CollectionUtils.isEmpty(bpImgList)) {
            for(YxBankerProductImg bpi : bpImgList) {
                YxProductImg pi = new YxProductImg();
                pi.setProductId(productId);
                pi.setImgUrl(bpi.getImgUrl());
                pi.setSort(bpi.getSort());
                pi.setFileType(bpi.getFileType());
                pi.setType(bpi.getType());
                pi.setCreateTime(new Date());
                productImgMapper.insertSelective(pi);
            }
        }

        // 3.同步商品spec
//        if (updateCount > 0){
//            productSpecMapper.deleteByProductId(productId);
//        }
        Example productSpecExample = new Example(YxProductSpec.class);
        productSpecExample.createCriteria().andEqualTo("productId", productId).andNotEqualTo("status",(byte) 3);
        List<YxProductSpec> productSpecList = productSpecMapper.selectByExample(productSpecExample);

        Example bankerProductSpecExample = new Example(YxBankerProductSpec.class);
        bankerProductSpecExample.createCriteria().andEqualTo("productId", product.getId()).andNotEqualTo("status",(byte) 3);
        List<YxBankerProductSpec> bpSpecList = bankerProductSpecMapper.selectByExample(bankerProductSpecExample);

        List<YxBankerProductSpec> noHandleList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(productSpecList) && !CollectionUtils.isEmpty(bpSpecList)) {
            productSpecList.stream().forEach(item -> {
                List<YxBankerProductSpec> collect = bpSpecList.stream().filter(bpSpec -> bpSpec.getId().equals(item.getSupplyId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect)){
                    YxBankerProductSpec yxBankerProductSpec = collect.get(0);
                    item.setSkuSpec(yxBankerProductSpec.getSkuSpec());
                    // 原价
                    item.setOriginalPrice(yxBankerProductSpec.getOriginalPrice());
                    // 同步供应商商品-规格-成本价格
                    item.setCostPrice(yxBankerProductSpec.getPrice());
                    item.setProImg(yxBankerProductSpec.getProImg());
                    item.setStock(yxBankerProductSpec.getStock());
                    item.setStatus(yxBankerProductSpec.getStatus().intValue());
                    item.setBankerProductId(yxBankerProductSpec.getProductId());
                    item.setCreateTime(new Date());
                    item.setThreeSkuId(yxBankerProductSpec.getThreeSkuId());
                    item.setSalePrice(yxBankerProductSpec.getSalePrice());
                    item.setSupplyPrice(yxBankerProductSpec.getSupplyPrice());
                    item.setGoodsCode(yxBankerProductSpec.getGoodsCode());
                    item.setSupplyId(yxBankerProductSpec.getId());
                    productSpecMapper.updateByPrimaryKey(item);
                }
            });
            List<Integer> productSpecSupplyIds = new ArrayList<>();
            try {
                productSpecSupplyIds = productSpecList.stream().map(YxProductSpec::getSupplyId).collect(Collectors.toList());
            } catch (Exception e) {
                log.info("===product_spec supply_id property is null");
            }
            List<Integer> bankerProductSpecIds = bpSpecList.stream().map(YxBankerProductSpec::getId).collect(Collectors.toList());
            productSpecSupplyIds.stream().forEach(productSpecSupplyId ->{
                if (null != productSpecSupplyId && !bankerProductSpecIds.contains(productSpecSupplyId)){
                    Example productSpecexample = new Example(YxProductSpec.class);
//                    productSpecexample.createCriteria().andEqualTo("supplyId",productSpecSupplyId);
//                    productSpecMapper.deleteByExample(productSpecexample);
                    productSpecMapper.updateBySupplyId(productSpecSupplyId);
                }
            });

            List<Integer> finalProductSpecSupplyIds = productSpecSupplyIds;
            bankerProductSpecIds.stream().forEach(bankerProductSpecId ->{
                if (!finalProductSpecSupplyIds.contains(bankerProductSpecId)){
                    YxProductSpec ps = new YxProductSpec();
                    List<YxBankerProductSpec> collect = bpSpecList.stream().filter(bpSpec -> bpSpec.getId().equals(bankerProductSpecId)).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collect)){
                        YxBankerProductSpec yxBankerProductSpec = collect.get(0);
                        ps.setProductId(productId);
                        ps.setSkuSpec(yxBankerProductSpec.getSkuSpec());
                        // 原价
                        ps.setOriginalPrice(yxBankerProductSpec.getOriginalPrice());
                        // 同步供应商商品-规格-成本价格
                        ps.setCostPrice(yxBankerProductSpec.getPrice());
                        ps.setProImg(yxBankerProductSpec.getProImg());
                        ps.setStock(yxBankerProductSpec.getStock());
                        ps.setStatus(yxBankerProductSpec.getStatus().intValue());
                        ps.setBankerProductId(yxBankerProductSpec.getProductId());
                        ps.setCreateTime(new Date());
                        ps.setThreeSkuId(yxBankerProductSpec.getThreeSkuId());
                        ps.setSalePrice(yxBankerProductSpec.getSalePrice());
                        ps.setSupplyPrice(yxBankerProductSpec.getSupplyPrice());
                        ps.setGoodsCode(yxBankerProductSpec.getGoodsCode());
                        ps.setSupplyId(yxBankerProductSpec.getId());
                        ps.setMarketPrice(yxBankerProductSpec.getMarketPrice());
                        productSpecMapper.insertSelective(ps);
                    }
                }
            });


        }else if (CollectionUtils.isEmpty(productSpecList) && !CollectionUtils.isEmpty(bpSpecList)) {
            for(YxBankerProductSpec bps : bpSpecList) {
                YxProductSpec ps = new YxProductSpec();
                ps.setProductId(productId);
                ps.setSkuSpec(bps.getSkuSpec());
                // 原价
                ps.setOriginalPrice(bps.getOriginalPrice());
                // 同步供应商商品-规格-成本价格
                ps.setCostPrice(bps.getPrice());
                ps.setProImg(bps.getProImg());
                ps.setStock(bps.getStock());
                ps.setStatus(bps.getStatus().intValue());
                ps.setBankerProductId(bps.getProductId());
                ps.setCreateTime(new Date());
                ps.setThreeSkuId(bps.getThreeSkuId());
                ps.setSalePrice(bps.getSalePrice());
                ps.setSupplyPrice(bps.getSupplyPrice());
                ps.setGoodsCode(bps.getGoodsCode());
                ps.setSupplyId(bps.getId());
                ps.setMarketPrice(bps.getMarketPrice());
                productSpecMapper.insertSelective(ps);
            }
        }
//        if (CollectionUtils.isEmpty(noHandleList)) {
//            for(YxBankerProductSpec bps : bpSpecList) {
//                YxProductSpec ps = new YxProductSpec();
//                ps.setProductId(productId);
//                ps.setSkuSpec(bps.getSkuSpec());
//                // 原价
//                ps.setOriginalPrice(bps.getOriginalPrice());
//                // 同步供应商商品-规格-成本价格
//                ps.setCostPrice(bps.getPrice());
//                ps.setProImg(bps.getProImg());
//                ps.setStock(bps.getStock());
//                ps.setStatus(bps.getStatus().intValue());
//                ps.setBankerProductId(bps.getProductId());
//                ps.setCreateTime(new Date());
//                ps.setThreeSkuId(bps.getThreeSkuId());
//                ps.setSalePrice(bps.getSalePrice());
//                ps.setSupplyPrice(bps.getSupplyPrice());
//                ps.setGoodsCode(bps.getGoodsCode());
//
//                productSpecMapper.insertSelective(ps);
//            }
//        }

//        if(!CollectionUtils.isEmpty(bpSpecList)) {
//            for(YxBankerProductSpec bps : bpSpecList) {
//                YxProductSpec ps = new YxProductSpec();
//                ps.setProductId(productId);
//                ps.setSkuSpec(bps.getSkuSpec());
//                // 原价
//                ps.setOriginalPrice(bps.getOriginalPrice());
//                // 同步供应商商品-规格-成本价格
//                ps.setCostPrice(bps.getPrice());
//                ps.setProImg(bps.getProImg());
//                ps.setStock(bps.getStock());
//                ps.setStatus(bps.getStatus().intValue());
//                ps.setBankerProductId(bps.getProductId());
//                ps.setCreateTime(new Date());
//                ps.setThreeSkuId(bps.getThreeSkuId());
//                ps.setSalePrice(bps.getSalePrice());
//                ps.setSupplyPrice(bps.getSupplyPrice());
//                ps.setGoodsCode(bps.getGoodsCode());
//
//                productSpecMapper.insertSelective(ps);
//            }
//        }

        // 4.同步商品sku_key
        if (updateCount > 0){
            productSkuKeyMapper.deleteByProductId(productId);
            productSkuValueMapper.deleteByProductId(productId);
        }
        Example bankerProductSkuKeyExample = new Example(YxBankerProductSkuKey.class);
        bankerProductSkuKeyExample.createCriteria().andEqualTo("pid", product.getId());
        List<YxBankerProductSkuKey> bpskList = bankerProductSkuKeyMapper.selectByExample(bankerProductSkuKeyExample);
        if(!CollectionUtils.isEmpty(bpskList)) {
            for(YxBankerProductSkuKey bpsk : bpskList) {
                YxProductSkuKey psk = new YxProductSkuKey();
                psk.setPid(productId);
                psk.setKid(bpsk.getKid());
                psk.setName(bpsk.getName());
                psk.setSort(bpsk.getSort());
                psk.setCreateTime(new Date());
                productSkuKeyMapper.insertSelective(psk);
                // 5.同步商品sku_value
                Example bankerProductSkuValueExample = new Example(YxBankerProductSkuValue.class);
                bankerProductSkuValueExample.createCriteria().andEqualTo("pid", product.getId()).andEqualTo("kid", bpsk.getId()).andEqualTo("status", (byte) 1);
                List<YxBankerProductSkuValue> bpsvList = bankerProductSkuValueMapper.selectByExample(bankerProductSkuValueExample);
                if(!CollectionUtils.isEmpty(bpsvList)) {
                    for(YxBankerProductSkuValue bpsv : bpsvList) {
                        YxProductSkuValue psv = new YxProductSkuValue();
                        psv.setPid(productId);
                        psv.setVid(bpsv.getVid());
                        psv.setKid(psk.getId());
                        psv.setValue(bpsv.getValue());
                        psv.setSort(bpsv.getSort());
                        psv.setStatus(bpsv.getStatus());
                        psv.setCreateTime(new Date());
                        productSkuValueMapper.insertSelective(psv);
                    }
                }
            }
        }

        // 6.消息通知 供应商商品-->普通商品库
        YxBankerMessage message = new YxBankerMessage();
        message.setBankerId(product.getBankerId());
        message.setBankerProductId(product.getId());
        message.setProductName(product.getProductName());
        message.setRemarks("您的商品："+product.getProductName()+" 已成功通过审核！");
        message.setStatus(0);
        message.setType(1);
        message.setCreateTime(new Date());
        bankerMessageMapper.insert(message);

        // 7.商品审核通过，供应商商品状态修改为审核通过状态 官网栏目也做同步
        bankerProductMapper.updateAuditStatus(product.getId(), 1,product.getAppraisalType());
        bankerProductMapper.synvBankerColumn(product.getId(), product.getBankerColumnId());

        // 8.供应商商品总数 +1
        bankerMapper.addProductNum(product.getBankerId());

        // 9.同步供应商 0元适用商品数量
        Integer zeroNum = productMapper.getZeroCount(product.getBankerId());
        bankerMapper.syncZeroNum(product.getBankerId(), zeroNum);

        bankerApplyMapper.deleteBankerApplyByBankerProductId(bankerProduct.getId());

        // 10.审核选择所属专区后，默认添加该商品至专区商品列表中
//        YxProductSpecial productSpecial = new ProductSpecial();
//        productSpecial.setSpecialId(product.getSpecialId());
//        productSpecial.setProductId(productId);
//        productSpecial.setType("COMMON");
//        productSpecial.setRecommendFlag(0);
//        productSpecial.setSort(1);
//        productSpecial.setStatus((byte) 2);
//        productSpecial.setCreateTime(new Date());
//        productSpecial.setUpdateTime(new Date());
//        productSpecialMapper.insertSelective(productSpecial);
        bankerProductMapper.updateAuditorById(bankerProduct.getId(),product.getAdmin());

        // 11.对比供应商商品修改前后信息
        try {
            checkProductMsgByBanker(bankerProduct.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return insertCount > 0 ? insertCount: updateCount;
    }

    /**
     * 更新供应链商品状态
     * @param request
     * @return
     */
    @Transactional
    public CommonResult productStatusUpdate(SupplyChainProductUpdateStatusRequest request) {
        if (0 == request.getStatus().intValue()) {
            request.setStatus(2);
        }
        List<Integer> bankerProductIds = new ArrayList<>();
        Example example = new Example(YxProduct.class);
        example.createCriteria().andIn("id", request.getIds());
        List<YxProduct> products = productMapper.selectByExample(example);
        if (1 == request.getStatus().intValue()) {
            if (products.stream().filter(item -> null == item.getSupplyPrice()).collect(Collectors.toList()).size() > 0) {
                return CommonResult.failed("请完善商品供货价");
            }
        }
        Example example1 = new Example(YxProductSpec.class);
        example1.createCriteria().andIn("productId", request.getIds());
        List<YxProductSpec> specList = productSpecMapper.selectByExample(example1);
        if (1 == request.getStatus().intValue()) {
            if (specList.stream().filter(item -> null == item.getSupplyPrice()).collect(Collectors.toList()).size() > 0) {
                return CommonResult.failed("请完善商品规格供货价");
            }
        }
        bankerProductIds = products.stream().map(YxProduct::getBankerProductId).collect(Collectors.toList());
        int count = productMapper.updateProductStatusByIds(request.getIds(), request.getStatus(), request.getOutOfSelection());
        bankerProductMapper.updateStatusByProductId(bankerProductIds, request.getStatus(), request.getOutOfSelection());
       /* //调用团购渠道接口，下架团购渠道的商品
        if(count > 0){
            String s = this.downProductForTuan(request.getIds());
        }*/
        if (!CollectionUtils.isEmpty(bankerProductIds)) {
            YxBankerProduct bankerProduct = bankerProductMapper.selectByPrimaryKey(bankerProductIds.get(0));
            YxBankerMessage message = new YxBankerMessage();
            message.setBankerId(products.get(0).getBankerId());
            message.setBankerProductId(bankerProductIds.get(0));
            message.setProductName(bankerProduct.getProductName());
            if (request.getStatus().equals(2)) {
                message.setRemarks("您的商品："+bankerProduct.getProductName()+" 已下架，原因：" + request.getOutOfSelection() + "。");
            }else if (request.getStatus().equals(1)) {
                message.setRemarks("您的商品：" + bankerProduct.getProductName()+" 已上架。");
            }
            message.setStatus(0);
            message.setType(1);
            message.setCreateTime(new Date());
            bankerMessageMapper.insert(message);
        }
        try {
            if (2 == request.getStatus().intValue() && !CollectionUtils.isEmpty(bankerProductIds)) {
                log.info("===调用销售端商品下架===", Joiner.on(",").join(bankerProductIds));
                downShopProduct(Joiner.on(",").join(bankerProductIds), request.getOutOfSelection());
                bankerProductIds.forEach(id ->{
                    sendMsgToSalesPlace(id,14);
                });
            }
        } catch (Exception e) {
            log.error("===调用销售端下架商品失败==={}", Joiner.on(",").join(bankerProductIds));
        }

        return count > 0 ? CommonResult.success() : CommonResult.failed("操作失败，请稍后重试");
    }

    public void updateProductStatusByBankerProductId(SupplyChainProductUpdateStatusRequest request) {
        bankerProductMapper.updateStatusByProductId(request.getIds(), request.getStatus(), request.getOutOfSelection());
        Example example = new Example(YxProduct.class);
        example.createCriteria().andIn("bankerProductId", request.getIds());
        List<YxProduct> products = productMapper.selectByExample(example);
        List<Integer> productIds = products.stream().map(YxProduct::getId).collect(Collectors.toList());
        int i = productMapper.updateProductStatusByIds(productIds, request.getStatus(), request.getOutOfSelection());
      /*  //调用团购渠道接口，下架团购渠道的商品
        if (i > 0) {
            String s = this.downProductForTuan(productIds);
        }*/
        sendMessage(products);
        try {
            if (2 == request.getStatus().intValue() && !CollectionUtils.isEmpty(request.getIds())) {
                log.info("===调用销售端商品下架===", Joiner.on(",").join(request.getIds()));
                downShopProduct(Joiner.on(",").join(request.getIds()),request.getOutOfSelection());
            }
        } catch (Exception e) {
            log.error("===调用销售端下架商品失败==={}", Joiner.on(",").join(request.getIds()));
        }
    }

    /**
    * 回调团购渠道接口，下架商品
    * @param
    * @returns:
    * 
    */
   /* public String downProductForTuan(List<Integer> productIds){
        String result = "";
        try {
            Map<String, Object> notifyParam = new HashMap<>();
            notifyParam.put("supplyIds", productIds);
            notifyParam.put("outOfSelection", "供应链主动下架商品");
            notifyParam.put("status", 2);
            result =  HttpClientUtil.doPostJson(circleApiConfig.getUrl() + "/callback/app/downProduct", JSON.toJSONString(notifyParam));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }*/

    public void sendMessage(List<YxProduct> products) {
        products.stream().forEach(product -> {
            YxBankerMessage message = new YxBankerMessage();
            message.setBankerId(product.getBankerId());
            message.setBankerProductId(product.getId());
            message.setProductName(product.getProductName());
            message.setRemarks("您的商品："+product.getProductName()+" 已成功通过审核！");
            message.setStatus(0);
            message.setType(1);
            message.setCreateTime(new Date());
            bankerMessageMapper.insert(message);
        });
    }

    /**
     * 商品下架
     * @param request
     * @return
     */
    public CommonResult productStatusDown(SupplyChainProductUpdateStatusRequest request) {
        List<Integer> ids = request.getIds();
        ids.stream().forEach(item -> {
            bankerApplyMapper.applyStatus(item, 2);
            SupplyChainProductUpdateStatusRequest req = new SupplyChainProductUpdateStatusRequest();
            req.setIds(Arrays.asList(item));
            req.setStatus(2);
            req.setOutOfSelection(request.getOutOfSelection());
            updateProductStatusByBankerProductId(req);
            //发信息到销售端
            YxProduct yxProduct = productMapper.selectByPrimaryKey(item);
            sendMsgToSalesPlace(yxProduct.getBankerProductId(),14);
        });
        return CommonResult.success();
    }

    public FreightTemplateResponse findFreightTemplateResponse(Integer id) {
        Example example = new Example(YxProduct.class);
        example.createCriteria().andEqualTo("bankerProductId",id);
        example.setOrderByClause("id desc limit 1");
        YxProduct yxProduct = productMapper.selectOneByExample(example);
        ProductSelectDetailResponse productSelectDetailResponse =productMapper.findProductSelectDetail(yxProduct.getId());
        if (productSelectDetailResponse!=null){
            FreightTemplateResponse freight = productMapper.findFreight(productSelectDetailResponse.getFreightId());
            if (null != freight && null != freight.getId()){
                List<YxAssignFreight> yxAssignFreightList = freightTemplateDao.queryYxAssignFreightByFreightId(freight.getId());
                List<YxAssignFreightResponse> yxAssignFreightResponses = new ArrayList<>();
                yxAssignFreightList.stream().forEach(yxAssignFreight ->{
                    YxAssignFreightResponse yxAssignFreightResponse = new YxAssignFreightResponse();
                    BeanUtils.copyProperties(yxAssignFreight, yxAssignFreightResponse);
                    yxAssignFreightResponses.add(yxAssignFreightResponse);

                });
                freight.setAssignFreightList(yxAssignFreightResponses);
            }
            return freight;
        }
        return null;
    }

    public FreightTemplateResponse findFreightTemplateResponseById(Integer id) {
        FreightTemplateResponse freight = productMapper.findFreight(id);
        if (null != freight && null != freight.getId()) {
            List<YxAssignFreight> yxAssignFreightList = freightTemplateDao.queryYxAssignFreightByFreightId(freight.getId());
            List<YxAssignFreightResponse> yxAssignFreightResponses = new ArrayList<>();
            yxAssignFreightList.stream().forEach(yxAssignFreight -> {
                YxAssignFreightResponse yxAssignFreightResponse = new YxAssignFreightResponse();
                BeanUtils.copyProperties(yxAssignFreight, yxAssignFreightResponse);
                yxAssignFreightResponses.add(yxAssignFreightResponse);

            });
            freight.setAssignFreightList(yxAssignFreightResponses);
        }
        return freight;
    }

    public Integer getAddressId(Integer productId) {
        return productMapper.getAddressId(productId);
    }

    public YxBankerStoreAddress getAddress(Integer addressId) {
        if (null == addressId){
            return null;
        }
        YxBankerStoreAddress address = productMapper.getAddress(addressId);
        if (null != address){
            address.setPCAaddress((null == address.getProvince() ? "" : address.getProvince())
                    + (null == address.getCity() ? "" : address.getCity())
                    + (null == address.getArea() ? "" : address.getArea())
                    + address.getAddress());
            return address;
        }
        return null;
    }

    public Map<Integer,YxBankerStoreAddress> getAddressForMap(Set<Integer> addressIds) {
        if (addressIds.isEmpty()){
            return Collections.EMPTY_MAP;
        }
        List<YxBankerStoreAddress> addressList = productMapper.getAddressForMap(addressIds);
        Map<Integer,YxBankerStoreAddress> addressMap = Maps.newHashMap();
        addressList.stream().forEach(address ->{
            address.setPCAaddress((null == address.getProvince() ? "" : address.getProvince())
                    + (null == address.getCity() ? "" : address.getCity())
                    + (null == address.getArea() ? "" : address.getArea())
                    + address.getAddress());
            addressMap.put(address.getId(),address);
        });
        return addressMap;
    }

    public List<BankerResponse> getBankerMsg(BankerRequest bankerRequest) {
        return  productMapper.selectBankerMsgByBankerId(bankerRequest.getBankerIdList());
    }

    public List<BankerProductQueryVo> getBankerProductId(BankerProductQueryDto dto) {
        return productMapper.getBankerProductIdByIds(dto.getProductIds());
    }

    public List<ProductSpecStockQureyResponse> getSpecStock(ProductSpecStockQureyRequest request) {
        return productSpecMapper.getSpecStock(request.getSupplyIds());
    }

    public List<YxProduct> getByIds(List<Integer> productIds) {
        List<YxProduct> yxProducts = productMapper.getProductInfoByIds(productIds);
        yxProducts.stream().forEach(yxProduct -> {
            Integer productAllSpecStock = productSpecMapper.selectProductAllSpecStock(yxProduct.getId());
            yxProduct.setStock(productAllSpecStock);
        });
        return yxProducts;
    }

    public List<Integer> getProductIdsByProductLabelId(Integer productLabelId) {
        Example example = new Example(YxProductLabelProduct.class);
        example.createCriteria().andEqualTo("productLabelId",productLabelId);
        List<YxProductLabelProduct> yxProductLabelProducts = productLabelProductMapper.selectByExample(example);
        List<Integer> productIds = yxProductLabelProducts.stream().filter(yxProductLabelProduct -> null != yxProductLabelProduct.getProductId()).map(YxProductLabelProduct::getProductId).collect(Collectors.toList());
        return productIds;
    }

    public List<SupplyProductLabelResponse> getSupplyProductLabelByProductIds(List<Integer> productIds) {
        List<SupplyProductLabelResponse> responses = new ArrayList<>();
        Example example = new Example(YxProductLabelProduct.class);
        example.createCriteria().andIn("productId", productIds);
        List<YxProductLabelProduct> yxProductLabelProducts = productLabelProductMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(yxProductLabelProducts)) {
            yxProductLabelProducts.stream().forEach(yxProductLabelProduct -> {
                List<Integer> productLabelIds = yxProductLabelProducts.stream().filter(item ->item.getProductId().equals(yxProductLabelProduct.getProductId())).map(YxProductLabelProduct::getProductLabelId).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(productLabelIds)){
                    Example productLabelExample = new Example(YxProductLabel.class);
                    productLabelExample.createCriteria().andIn("productLabelId",productLabelIds);
                    List<YxProductLabel> productLabels = productLabelMapper.selectByExample(productLabelExample);
                    if (!CollectionUtils.isEmpty(productLabels)){
                        SupplyProductLabelResponse supplyProductLabelResponse = new SupplyProductLabelResponse();
                        supplyProductLabelResponse.setProductId(yxProductLabelProduct.getProductId());
                        supplyProductLabelResponse.setSupplyProductLabelName(Joiner.on(",").join(productLabels.stream().map(YxProductLabel::getProductLabelName).collect(Collectors.toList())));
                        responses.add(supplyProductLabelResponse);
                    }
                }
            });
        }
        return responses;
    }

    public void checkProductStockFrozen() {
        stockFrozenRecordMapper.updateObsolete();
    }

    public boolean checkSpec(List<Integer> supplyIds,Integer supplyProductId) {
        Example example = new Example(YxProductSpec.class);
        example.createCriteria().andEqualTo("productId",supplyProductId).andNotEqualTo("status",(byte)3);
        List<YxProductSpec> yxProductSpecs = productSpecMapper.selectByExample(example);
        AtomicBoolean flag = new AtomicBoolean(false);
        //如果渠道和供应链的商品规格数量相等
        if (yxProductSpecs.size() == supplyIds.size()){
            yxProductSpecs.stream().forEach(item ->{
                //如果供应链有不存在于渠道的商品规格
                if (!supplyIds.contains(item.getId())){
                    flag.set(true);
                }
            });
        }else {//如果渠道和供应链的商品规格数量不相等
            flag.set(true);
        }
        return flag.get();
    }

    public CommonResult getProductStock(String bankerProductId) {
        List<String> bankerProductIdList = Arrays.asList(bankerProductId.split(","));
        List<Integer> bankerProductIds = bankerProductIdList.stream().map(Integer::parseInt).collect(Collectors.toList());
        Example example = new Example(YxProduct.class);
        example.createCriteria().andIn("bankerProductId", bankerProductIds);
        example.selectProperties("bankerProductId", "stock");
        List<YxProduct> productList = productMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(productList)) {
            return CommonResult.failed("找不到商品信息");
        }
        List<ProductStockResponse> resultList = new ArrayList<>();
        productList.stream().forEach(item -> {
            ProductStockResponse response = new ProductStockResponse();
            response.setBankerProductId(item.getBankerProductId());
            response.setStock(item.getStock());
            resultList.add(response);
        });
        return CommonResult.success(resultList);
    }

    public CommonResult updateImgToTable(String type) {
        final Integer[] sum = {0};
        if (type.equals("1")){
            Example example = new Example(YxBankerProductImg.class);
            example.createCriteria().andEqualTo("type","info").andIsNotNull("imgUrl");
            example.selectProperties("productId","imgUrl");
            List<YxBankerProductImg> yxBankerProductImgs = bankerProductImgMapper.selectByExample(example);
            yxBankerProductImgs.stream().forEach(item ->{
                item.setImgUrl("<img src=\""+item.getImgUrl()+"\">");
            });
            Set<Integer> collect = yxBankerProductImgs.stream().map(YxBankerProductImg::getProductId).collect(Collectors.toSet());
            List<Integer> productIdList = new ArrayList<>(collect);
            productIdList.stream().forEach(item ->{
                String infoImg = "";
                List<String> imgUrlList = yxBankerProductImgs.stream().filter(yxBankerProductImg -> yxBankerProductImg.getProductId().equals(item)).map(YxBankerProductImg::getImgUrl).collect(Collectors.toList());
                for (String s : imgUrlList) {
                    infoImg = infoImg + s;
                }
                String infoImgFinal = "<p><br></p><p>" + infoImg + "</p>";
                Integer count = bankerProductMapper.updateInfoImgById(item,infoImgFinal);
                sum[0] = sum[0] + count;
            });
            return CommonResult.success(sum[0]);
        }else {
            Example example = new Example(YxProductImg.class);
            example.createCriteria().andEqualTo("type","info").andIsNotNull("imgUrl");
            example.selectProperties("productId","imgUrl");
            List<YxProductImg> yxProductImgs = productImgMapper.selectByExample(example);
            yxProductImgs.stream().forEach(item ->{
                item.setImgUrl("<img src=\""+item.getImgUrl()+"\">");
            });
            Set<Integer> collect = yxProductImgs.stream().map(YxProductImg::getProductId).collect(Collectors.toSet());
            List<Integer> productIdList = new ArrayList<>(collect);
            productIdList.stream().forEach(item ->{
                String infoImg = "";
                List<String> imgUrlList = yxProductImgs.stream().filter(yxBankerProductImg -> yxBankerProductImg.getProductId().equals(item)).map(YxProductImg::getImgUrl).collect(Collectors.toList());
                for (String s : imgUrlList) {
                    infoImg = infoImg + s;
                }
                String infoImgFinal = "<p><br></p><p>" + infoImg + "</p>";
                Integer count = productMapper.updateInfoImgById(item, infoImgFinal);
                sum[0] = sum[0] + count;
            });
            return CommonResult.success(sum[0]);
        }
//        if (type.equals("1")){
//            Example example = new Example(YxBankerProduct.class);
//            example.selectProperties("id");
//            List<YxBankerProduct> yxBankerProducts = bankerProductMapper.selectByExample(example);
//            List<Integer> bankerProductIds = yxBankerProducts.stream().map(YxBankerProduct::getId).collect(Collectors.toList());
//            bankerProductIds.stream().forEach(bankerProductId ->{
//                final String[] infoImg = {""};
//                Example example1 = new Example(YxBankerProductImg.class);
//                example1.createCriteria().andEqualTo("productId",bankerProductId).andIsNotNull("imgUrl");
//                example1.selectProperties("imgUrl");
//                List<YxBankerProductImg> yxBankerProductImgs = bankerProductImgMapper.selectByExample(example1);
//                if (!CollectionUtils.isEmpty(yxBankerProductImgs)){
//                    yxBankerProductImgs.stream().filter(yxBankerProductImg ->null != yxBankerProductImg.getImgUrl()).forEach(yxBankerProductImg -> {
//                        yxBankerProductImg.setImgUrl("<img src=\""+yxBankerProductImg.getImgUrl()+"\">");
//                        infoImg[0] = infoImg[0] +  yxBankerProductImg.getImgUrl();
//                    });
//                    String infoImgFinal = "<p><br></p><p>" + infoImg[0] + "</p>";
//                    Integer count = bankerProductMapper.updateInfoImgById(bankerProductId,infoImgFinal);
//                    sum[0] = sum[0] + count;
//                }
//            });
//            return CommonResult.success(sum[0]);
//        }else {
//            Example example = new Example(YxProduct.class);
//            example.selectProperties("id");
//            List<YxProduct> yxProducts = productMapper.selectByExample(example);
//            List<Integer> productIds = yxProducts.stream().map(YxProduct::getId).collect(Collectors.toList());
//            productIds.stream().forEach(productId ->{
//                final String[] infoImg = {""};
//                Example example1 = new Example(YxBankerProductImg.class);
//                example1.createCriteria().andEqualTo("productId",productId).andIsNotNull("imgUrl");
//                example1.selectProperties("imgUrl");
//                List<YxProductImg> yxProductImgs = productImgMapper.selectByExample(example1);
//                if (!CollectionUtils.isEmpty(yxProductImgs)){
//                    yxProductImgs.stream().filter(yxProductImg ->null != yxProductImg.getImgUrl()).forEach(yxProductImg -> {
//                        yxProductImg.setImgUrl("<img src=\""+yxProductImg.getImgUrl()+"\">");
//                        infoImg[0] = infoImg[0] +  yxProductImg.getImgUrl();
//                    });
//                    String infoImgFinal = "<p><br></p><p>" + infoImg[0] + "</p>";
//                    Integer count = productMapper.updateInfoImgById(productId,infoImgFinal);
//                    sum[0] = sum[0] + count;
//                }
//            });
//            return CommonResult.success(sum[0]);
//        }
    }

    public CommonResult findCountryAll() {
        return CommonResult.success(productMapper.findCountryAll());
    }

    public List<Integer> getFreightTemplateProduct() {
       return  bankerProductMapper.getFreightTemplateProduct();
    }

    /**
     * 供应商商品信息对比
     */
    @Async
    public void checkProductMsgByBanker(Integer bankerProductId){
        String bankerProductKey = "bankerProduct:banker_product_key_" + bankerProductId;
        String bankerProductStr = redisService.get(bankerProductKey);
        if (StringUtils.isEmpty(bankerProductStr)){
            return;
        }
        YxBankerProduct bankerProductOld = JSONObject.parseObject(bankerProductStr, YxBankerProduct.class);
        YxBankerProduct bankerProductNew = bankerProductMapper.selectByPrimaryKey(bankerProductId);


        if (null == bankerProductOld.getBrandId()){
            bankerProductOld.setBrandId(0);
        }
        if (null == bankerProductNew.getBrandId()){
            bankerProductNew.setBrandId(0);
        }

        //属性信息
        Boolean properlyFlag = false;
        //款号
        if (!bankerProductOld.getTypeno().equals(bankerProductNew.getTypeno())){
            properlyFlag = true;
        }
        //一级分类
        else if (bankerProductOld.getTopCategoryId().compareTo(bankerProductNew.getTopCategoryId()) != 0){
            properlyFlag = true;
        }
        //二级分类
        else if (bankerProductOld.getCategoryId().compareTo(bankerProductNew.getCategoryId()) != 0){
            properlyFlag = true;
        }
        //三级分类
        else if (bankerProductOld.getBottomCategoryId().compareTo(bankerProductNew.getBottomCategoryId()) != 0){
            properlyFlag = true;
        }
        //商品品牌
        else if (bankerProductOld.getBrandId().compareTo(bankerProductNew.getBrandId()) != 0){
            properlyFlag = true;
        }
        //库存预警
        else if (bankerProductOld.getStockWarning().compareTo(bankerProductNew.getStockWarning()) != 0){
            properlyFlag = true;
        }
        //是否控价
        else if (bankerProductOld.getControlPrice().compareTo(bankerProductNew.getControlPrice()) != 0){
            properlyFlag = true;
        }
        //商品类型
        else if (bankerProductOld.getIsExit().compareTo(bankerProductNew.getIsExit()) != 0) {
            properlyFlag = true;
        }
        //邮寄类型（mailType）：一般贸易，直邮，保税
        else if (!bankerProductOld.getMailType().equals(bankerProductNew.getMailType())){
            properlyFlag = true;
        }
        //邮寄备注：mailNote
        else if (!bankerProductOld.getMailNote().equals(bankerProductNew.getMailNote())){
            properlyFlag = true;
        }
        //海关商品编号
        else if (!bankerProductOld.getCustomsNo().equals(bankerProductNew.getCustomsNo())){
            properlyFlag = true;
        }
        //所属国家编号
        else if (!bankerProductOld.getCountryCode().equals(bankerProductNew.getCountryCode())){
            properlyFlag = true;
        }
        //计量单位编号
        else if (!bankerProductOld.getUnitCode().equals(bankerProductNew.getUnitCode())){
            properlyFlag = true;
        }
        //跨境电商综合税率
        else if (bankerProductOld.getConsolidatedTaxRate().compareTo(bankerProductNew.getConsolidatedTaxRate()) != 0){
            properlyFlag = true;
        }

        //物流信息
        Boolean LogisticsFlag = false;
        //售后地址
        if (bankerProductOld.getAddressId().compareTo(bankerProductNew.getAddressId()) != 0){
            LogisticsFlag = true;
        }
        //运费
        else if (bankerProductOld.getFreightId().compareTo(bankerProductNew.getFreightId()) != 0){
            LogisticsFlag = true;
        }

        //sku信息
        AtomicBoolean skuFlag = new AtomicBoolean(false);
        Example example = new Example(YxBankerProductSpec.class);
        example.createCriteria().andEqualTo("productId", bankerProductId).andNotEqualTo("status", 3);
        List<YxBankerProductSpec> bankerProductSpecsNew = bankerProductSpecMapper.selectByExample(example);
        String bankerProductSpecKey = "banker_product_spec_key_" + bankerProductId;
        String bankerProductSpecStr = redisService.get(bankerProductSpecKey);
        if (!StringUtils.isEmpty(bankerProductSpecStr)) {
            List<YxBankerProductSpec> bankerProductSpecsOld = JSONObject.parseArray(bankerProductSpecStr, YxBankerProductSpec.class);
            if (bankerProductSpecsOld.size() != bankerProductSpecsNew.size()) {
                skuFlag.set(true);
                return;
            }

            bankerProductSpecsOld.stream().forEach(old -> {
                if (skuFlag.get()) {
                    return;
                }
                List<YxBankerProductSpec> newForOld = bankerProductSpecsNew.stream().filter(newSpec -> newSpec.getId().equals(old.getId())).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(newForOld)) {
                    skuFlag.set(true);
                    return;
                }
                YxBankerProductSpec specNew = newForOld.get(0);
                if (!old.getGoodsCode().equals(specNew.getGoodsCode())) {
                    skuFlag.set(true);
                } else if (old.getPrice().compareTo(specNew.getPrice()) != 0) {
                    skuFlag.set(true);
                } else if (old.getOriginalPrice().compareTo(specNew.getOriginalPrice()) != 0) {
                    skuFlag.set(true);
                } else if (!old.getThreeSkuId().equals(specNew.getThreeSkuId())) {
                    skuFlag.set(true);
                } else if (old.getStock().compareTo(specNew.getStock()) != 0) {
                    skuFlag.set(true);
                } else if (old.getSalePrice().compareTo(specNew.getSalePrice()) != 0) {
                    skuFlag.set(true);
                }
            });
        }
        //发信息到销售端
        sendMsg(bankerProductId,properlyFlag,LogisticsFlag,skuFlag.get());
    }


    private void sendMsg(Integer bankerProductId,Boolean properlyFlag,Boolean LogisticsFlag, Boolean skuFlag ) {
        log.info("===========bankerProductId: {}=======properlyFlag: {}========LogisticsFlag: {}============skuFlag: {}======", bankerProductId, properlyFlag, LogisticsFlag, skuFlag);
        if (properlyFlag){
            sendMsgToSalesPlace(bankerProductId,11);
        }
        if (LogisticsFlag){
            sendMsgToSalesPlace(bankerProductId,13);
        }
        if (skuFlag){
            sendMsgToSalesPlace(bankerProductId,12);
        }
    }

    //供应链信息对比
    @Async
    public void checkProductMsgBySupply(GoodsRequest goodsRequest){
        @NotNull(message = "商品ID 不能为空！") Integer productId = goodsRequest.getId();
        String productKey = "product:supply_chain_product_key_" + productId;
        String productStr = redisService.get(productKey);
        if (StringUtils.isEmpty(productStr)){
            return;
        }
        Map map = JSONObject.parseObject(productStr, Map.class);
        String product = (String) map.get("product");
        YxProduct productOld = JSONObject.parseObject(product, YxProduct.class);
        YxProduct productNew1 = productMapper.selectByPrimaryKey(productId);

        YxBankerProduct bankerProduct = bankerProductMapper.selectByPrimaryKey(productNew1.getBankerProductId());
        productNew1.setControlPrice(bankerProduct.getControlPrice());
        productNew1.setAddressId(bankerProduct.getAddressId());
        productNew1.setFreightId(bankerProduct.getFreightId());

        if (null == productOld.getBrandId()){
            productOld.setBrandId(0);
        }
        if (null == productNew1.getBrandId()){
            productNew1.setBrandId(0);
        }

        //属性信息
        Boolean properlyFlag = false;
        //一级分类
        if (productNew1.getTopCategoryId().compareTo(productOld.getTopCategoryId()) != 0){
            properlyFlag = true;
        }
        //二级分类
        else if (productNew1.getCategoryId().compareTo(productOld.getCategoryId()) != 0){
            properlyFlag = true;
        }
        //三级分类
        else if (productNew1.getBottomCategoryId().compareTo(productOld.getBottomCategoryId()) != 0){
            properlyFlag = true;
        }
        //商品品牌
        else if (productNew1.getBrandId().compareTo(productOld.getBrandId()) != 0){
            properlyFlag = true;
        }
        //库存预警
        else if (productNew1.getStockWarning().compareTo(productOld.getStockWarning()) != 0){
            properlyFlag = true;
        }
        //是否控价
        else if (productNew1.getControlPrice().compareTo(productOld.getControlPrice()) != 0){
            properlyFlag = true;
        }
//        //商品类型
//        else if (productNew1.getIsExit().compareTo(productOld.getIsExit()) != 0) {
//            properlyFlag = true;
//        }
//        //邮寄类型（mailType）：一般贸易，直邮，保税
//        else if (!productNew1.getMailType().equals(productOld.getMailType())){
//            properlyFlag = true;
//        }
//        //邮寄备注：mailNote
//        else if (!productNew1.getMailNote().equals(productOld.getMailNote())){
//            properlyFlag = true;
//        }
//        //海关商品编号
//        else if (!productNew1.getCustomsNo().equals(productOld.getCustomsNo())){
//            properlyFlag = true;
//        }
//        //所属国家编号
//        else if (!productNew1.getCountryCode().equals(productOld.getCountryCode())){
//            properlyFlag = true;
//        }
//        //计量单位编号
//        else if (!productNew1.getUnitCode().equals(productOld.getUnitCode())){
//            properlyFlag = true;
//        }
//        //跨境电商综合税率
//        else if (productNew1.getConsolidatedTaxRate().compareTo(productOld.getConsolidatedTaxRate()) != 0){
//            properlyFlag = true;
//        }

        //物流信息
        Boolean LogisticsFlag = false;
        //售后地址
        if (productNew1.getAddressId().compareTo(productOld.getAddressId()) != 0){
            LogisticsFlag = true;
        }
        //运费
        else if (productNew1.getFreightId().compareTo(productOld.getFreightId()) != 0){
            LogisticsFlag = true;
        }


        AtomicBoolean skuFlag = new AtomicBoolean(false);
        String productSpecStr = (String) map.get("productSpecList");
        if (!StringUtils.isEmpty(productSpecStr)) {
            List<YxProductSpec> specOldList = JSONObject.parseArray(productSpecStr, YxProductSpec.class);
            Example example = new Example(YxProductSpec.class);
            example.createCriteria().andEqualTo("productId",productId);
            List<YxProductSpec> specNewList = productSpecMapper.selectByExample(example);
            if (specOldList.size() != specNewList.size()) {
                skuFlag.set(true);
                return;
            }

            specOldList.stream().forEach(old -> {
                if (skuFlag.get()) {
                    return;
                }
                List<YxProductSpec> newForOld = specNewList.stream().filter(newSpec -> newSpec.getId().equals(old.getId())).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(newForOld)) {
                    skuFlag.set(true);
                    return;
                }
                YxProductSpec specNew = newForOld.get(0);
                if (old.getSupplyPrice().compareTo(specNew.getSupplyPrice()) != 0) {
                    skuFlag.set(true);
                } else if (old.getOriginalPrice().compareTo(specNew.getOriginalPrice()) != 0) {
                    skuFlag.set(true);
                }  else if (old.getStock().compareTo(specNew.getStock()) != 0) {
                    skuFlag.set(true);
                } else if (old.getSalePrice().compareTo(specNew.getSalePrice()) != 0) {
                    skuFlag.set(true);
                }
            });
        }
        sendMsg(productOld.getBankerProductId(),properlyFlag,LogisticsFlag,skuFlag.get());
    }



    /**
     * 商品修改后发信息到销售渠道
     * @param bankerProductId 供应商商品id
     * @param msgType 信息类型 11.属性类信息 12.SKU信息 13.物流信息 14.下架通知 15.描述信息
     */
    public void sendMsgToSalesPlace(Integer bankerProductId, Integer msgType){
        Example notifyUrlInfoexample = new Example(YxNotifyUrlInfo.class);
        notifyUrlInfoexample.createCriteria().andEqualTo("type", 9);
        List<YxNotifyUrlInfo> notifyUrlInfos = notifyUrlInfoMapper.selectByExample(notifyUrlInfoexample);
        log.info("======商品修改后发信息到销售渠道======notifyUrlInfos={}", notifyUrlInfos);
        notifyUrlInfos.stream().forEach(item -> {
            Map<String, String> params = new HashMap<>();
            params.put("bankerProductId", bankerProductId.toString());
            params.put("msgType", msgType.toString());
            try {
                String result = HttpClientUtil.doGet(item.getUrl(), params);
                log.info("===params,result,url==={},{},{}",params, result, item.getUrl());
            } catch (Exception e) {
                log.error("===downShopProduct is error==={}",item.getUrl());
            }
        });
    }

    @Async
    public void updateProductLabelAndCategoryId(SupplyChainRequest request) {

        List<SupplyChainProductRequest> requests = request.getProductRequests();
        List<Integer> productIds = requests.stream()
                .filter(e -> null != e.getProductId())
                .map(SupplyChainProductRequest::getProductId)
                .collect(Collectors.toList());

        //导入的分类不存在的商品id
        List<Integer> productId = new ArrayList<>();

        //删除旧的标签
        Example productProductLabelExample = new Example(YxProductLabelProduct.class);
        productProductLabelExample.createCriteria().andIn("productId", productIds);
        List<YxProductLabelProduct> yxProductLabelProducts = productLabelProductMapper.selectByExample(productProductLabelExample);
        int count = 1;
        if (yxProductLabelProducts.size() > 0) {
            count = productLabelProductMapper.deleteByExample(productProductLabelExample);
        }
        //标签转集合
        Set<Integer> set = new HashSet<>();
        requests.stream().filter(e ->!StringUtils.isEmpty(e.getProductLabelIds())).forEach(e ->{
            String[] split = e.getProductLabelIds().split(",");
            for (String s : split) {
                set.add(Integer.valueOf(s));
            }
        });
        //查询存在的标签
        List<Integer> countLabelIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(set)){
            List<Integer> list = new ArrayList<>(set);
            countLabelIds = productLabelMapper.selectCountLabelByIds(list);
        }

        //获取导入的标签不存在的商品
        Map<Integer,List<String>> map = new HashMap<>();

        //重新设置标签
        List<Integer> finalCountLabelIds = countLabelIds;
        requests.stream().filter(e -> null != e.getProductId()).forEach(item ->{
            if (!StringUtils.isEmpty(item.getProductLabelIds())){
                String[] split = item.getProductLabelIds().split(",");
                List<Integer> productLabelIdList = new ArrayList<>();
                List<String> noCountIds = new ArrayList<>();
                for (String s : split) {
                    if (!CollectionUtils.isEmpty(finalCountLabelIds) && finalCountLabelIds.contains(Integer.parseInt(s))){
                        productLabelIdList.add(Integer.valueOf(s));
                    }else {
                        noCountIds.add(s);
                    }
                }
                if (!CollectionUtils.isEmpty(noCountIds)){
                    map.put(item.getProductId(),noCountIds);
                }
                if (!CollectionUtils.isEmpty(productLabelIdList)){
                    //批量插入标签
                    productLabelProductMapper.insertBatch(item.getProductId(),request.getAdminId(),productLabelIdList);
                }
            }
        });
        //导入的第三级分类id
        List<Integer> bottomCategoryIds = requests.stream()
                .filter(e -> null != e.getBottomCategoryId())
                .map(SupplyChainProductRequest::getBottomCategoryId)
                .collect(Collectors.toList());

        //根据导入的第三级分类获取第一第二级分类
        List<ProductCategoryDto> productCategoryDtoList = productCategoryService.getCategoryIdByBottomCategoryIds(bottomCategoryIds);

        //第三级分类存在的集合
        List<Integer> bottomCategoryIdList = productCategoryDtoList.stream().map(ProductCategoryDto::getBottomCategoryId).collect(Collectors.toList());
        //分类id为空的商品id
        List<Integer> nullCategoryProductIds = requests.stream().filter(e -> null == e.getBottomCategoryId()).map(SupplyChainProductRequest::getProductId).collect(Collectors.toList());

        //导入的分类不存在的商品id
        productId = requests.stream().filter(e -> null != e.getBottomCategoryId() && !bottomCategoryIdList.contains(e.getBottomCategoryId())).map(SupplyChainProductRequest::getProductId).collect(Collectors.toList());

        //获取商品信息
        List<YxProduct> yxProducts = productMapper.selectByProductIds(productIds);
        //重新设置第三级分类
        Map<Integer, List<SupplyChainProductRequest>> listMap = requests.stream()
                .filter(e ->null != e.getBottomCategoryId())
                .collect(Collectors.groupingBy(SupplyChainProductRequest::getBottomCategoryId));
        for (Map.Entry<Integer, List<SupplyChainProductRequest>> entry : listMap.entrySet()) {
            Optional<ProductCategoryDto> first = productCategoryDtoList.stream()
                    .filter(e -> entry.getKey().equals(e.getBottomCategoryId()))
                    .findFirst();
            if (first.isPresent()){
                List<Integer> productIdList = entry.getValue().stream()
                        .map(SupplyChainProductRequest::getProductId)
                        .collect(Collectors.toList());
                //获取导入的商品第三级分类id与原来不一样的商品
                List<YxProduct> productList = yxProducts.stream()
                        .filter(e -> productIdList.contains(e.getId()) && !e.getBottomCategoryId().equals(entry.getKey()))
                        .collect(Collectors.toList());
                if (CollectionUtils.isEmpty(productList)){
                    continue;
                }
                ProductCategoryDto dto = first.get();
                //修改供应链商品表
                List<Integer> supplyProductIds = productList.stream().map(YxProduct::getId).collect(Collectors.toList());
                productMapper.updateCategoryIdByIds(supplyProductIds,dto.getTopCategoryId(),dto.getCategoryId(),dto.getBottomCategoryId());
                //修改供应商商品表
                List<Integer> bankerProductIds = productList.stream().map(YxProduct::getBankerProductId).collect(Collectors.toList());
                bankerProductMapper.updateCategoryIdByIds(bankerProductIds,dto.getTopCategoryId(),dto.getCategoryId(),dto.getBottomCategoryId());
                //修改销售端商品表
                supplyProductIds.stream().forEach(item ->{
                    GoodsRequest goodsRequest = new GoodsRequest();
                    goodsRequest.setSupplyProductId(item);
                    goodsRequest.setTopCategoryId(dto.getTopCategoryId());
                    goodsRequest.setCategoryId(dto.getCategoryId());
                    goodsRequest.setBottomCategoryId(dto.getBottomCategoryId());
                    syncChannelProductMsg(goodsRequest);
                });
            }
        }
        List<Integer> finalProductId = productId;
        List<ProductImportInfoMsg> infoMsgs = requests.stream().map(item -> {
            ProductImportInfoMsg msg = new ProductImportInfoMsg();
            msg.setImportId(request.getImportId());
            msg.setProductId(item.getProductId());
            msg.setProductName(item.getProductName());
            msg.setCreateTime(new Date());

            //备注
            StringBuffer remark = new StringBuffer();
            if (finalProductId.contains(item.getProductId()) && !nullCategoryProductIds.contains(item.getProductId())){
                remark.append("分类ID" + item.getBottomCategoryId() + "不存在");
            }
            if (nullCategoryProductIds.contains(item.getProductId())){
                remark.append("分类ID为空");
            }
            List<String> strings = map.get(item.getProductId());
            if (!CollectionUtils.isEmpty(strings)){
                String join = String.join(",", strings);
                if (remark.length() > 0){
                    remark.append("，");
                }
                remark.append("标签ID"+join+"不存在");
            }
            if (remark.length() == 0){
                remark.append("完成");
            }
            msg.setRemark(remark.toString());
            return msg;
        }).collect(Collectors.toList());
        //插入详情表
        productImportInfoMsgMapper.insertBatch(infoMsgs);
        //完成后修改记录表状态
        long count1 = infoMsgs.stream().filter(e -> e.getRemark().length() > 2).count();
        productImportMsgMapper.updateStatusById(request.getImportId(),count1);
        log.info("================excelImport2=================");
    }

    /**
     * 保存导入信息
     * @param request
     * @return
     */
    public ProductImportMsg saveImportMsg(SupplyChainRequest request) {
        ProductImportMsg importMsg = new ProductImportMsg();
        importMsg.setFileName(request.getFileName());
        importMsg.setCreateTime(new Date());
        importMsg.setStatus(1);
        importMsg.setProductNum(request.getProductRequests().size());
        int i = productImportMsgMapper.insertSelective(importMsg);
        return importMsg;
    }

    /**
     * 获取导入信息
     * @param pageNum
     * @param pageSize
     * @return
     */
    public CommonResult getImportMsg(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Example example = new Example(ProductImportMsg.class);
        example.setOrderByClause("id desc");
        List<ProductImportMsg> productImportMsgs = productImportMsgMapper.selectByExample(example);
        return CommonResult.success(CommonPage.restPage(productImportMsgs));
    }

    /**
     * 获取导入详情信息
     * @param id
     * @param pageNum
     * @param pageSize
     * @return
     */
    public CommonResult getImportInfoMsg(Integer id, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Example example = new Example(ProductImportInfoMsg.class);
        example.createCriteria().andEqualTo("importId",id);
        example.setOrderByClause("remark asc");
        List<ProductImportInfoMsg> productImportInfoMsgs = productImportInfoMsgMapper.selectByExample(example);
        return CommonResult.success(CommonPage.restPage(productImportInfoMsgs));
    }

    public void addProductReviews(ProductReviewsAddRequest request) {
        guchuangRabbitTemplate.convertAndSend(QueueConstants.ADD_PRODUCT_REVIEWS, JSONObject.toJSONString(request, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
//        jumaiduoRabbitTemplate.convertAndSend(QueueConstants.ADD_PRODUCT_REVIEWS, JSONObject.toJSONString(request, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
//        yiquanRabbitTemplate.convertAndSend(QueueConstants.ADD_PRODUCT_REVIEWS, JSONObject.toJSONString(request, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
//        zxlpRabbitTemplate.convertAndSend(QueueConstants.ADD_PRODUCT_REVIEWS, JSONObject.toJSONString(request, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
//        ygyxRabbitTemplate.convertAndSend(QueueConstants.ADD_PRODUCT_REVIEWS, JSONObject.toJSONString(request, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
//        yxhdRabbitTemplate.convertAndSend(QueueConstants.ADD_PRODUCT_REVIEWS, JSONObject.toJSONString(request, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
//        jckjRabbitTemplate.convertAndSend(QueueConstants.ADD_PRODUCT_REVIEWS, JSONObject.toJSONString(request, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
    }

    public void updateProductReviews(ProductReviewsUpdateRequest request) {
        guchuangRabbitTemplate.convertAndSend(QueueConstants.UPDATE_PRODUCT_REVIEWS, JSONObject.toJSONString(request, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
//        jumaiduoRabbitTemplate.convertAndSend(QueueConstants.UPDATE_PRODUCT_REVIEWS, JSONObject.toJSONString(request, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
//        yiquanRabbitTemplate.convertAndSend(QueueConstants.UPDATE_PRODUCT_REVIEWS, JSONObject.toJSONString(request, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
//        zxlpRabbitTemplate.convertAndSend(QueueConstants.UPDATE_PRODUCT_REVIEWS, JSONObject.toJSONString(request, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
//        ygyxRabbitTemplate.convertAndSend(QueueConstants.UPDATE_PRODUCT_REVIEWS, JSONObject.toJSONString(request, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
//        yxhdRabbitTemplate.convertAndSend(QueueConstants.UPDATE_PRODUCT_REVIEWS, JSONObject.toJSONString(request, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
//        jckjRabbitTemplate.convertAndSend(QueueConstants.UPDATE_PRODUCT_REVIEWS, JSONObject.toJSONString(request, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
    }

}
